PHP使用数组作为名称设置魔术方法 [英] PHP set magic method with array as names

查看:90
本文介绍了PHP使用数组作为名称设置魔术方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个类,该类将用于存储和加载一些设置.在类内部,所有设置都存储在一个数组中.设置可以嵌套,因此设置数组是多维数组.我想使用魔术方法__get和__set来存储和加载设置,因此这些设置可以充当类成员.但是,由于我使用的是嵌套方法,因此当我尝试访问嵌套设置时,无法使__set方法起作用.

I am creating a class which I will use to store and load some settings. Inside the class all settings are stored in an array. The settings can be nested, so the settings array is a multidimensional array. I want to store and load the settings using the magic methods __get and __set, so the settings can act as class members. However, since I'm using nested methods, I can't get the __set method to work when I try to access a nested setting.

该类是这样的:

class settings
{
    private $_settings = array();

    //some functions to fill the array

    public function __set($name, $value)
    {
        echo 'inside the __set method';
        //do some stuff
    }
}

以及使用此类的代码:

$foo = new settings();
//do some stuff with the class, so the internal settings array is as followed:
//array(
//    somename => somevalue
//    bar => array (
//               baz = someothervalue
//               qux = 42
//                 )
//     )
$foo->somename = something; //this works, __set method is called correctly
$foo->bar['baz'] = somethingelse; //Doesn't work, __set method isn't called at all

我如何才能使这最后一行起作用?

How can I get this last line to work?

推荐答案

使用此方法访问数组时,实际上是通过__get进行的.为了在返回的数组上设置参数,需要将其作为引用返回:&__get($name)

When accessing an array using this method, it actually goes through __get instead. In order to set a parameter on that array that was returned it needs to be returned as a reference: &__get($name)

除非您的意思是,您希望每个作为数组返回的项目都以与父对象相同的方式工作,在这种情况下,您应该查看Zend Framework的

Unless, what you mean is that you want each item that is returned as an array to act the same way as the parent object, in which case you should take a look at Zend Framework's Zend_Config object source for a good way to do that. (It returns a new instance of itself with the sub-array as the parameter).

这篇关于PHP使用数组作为名称设置魔术方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆