Php 使用_集合解决数组问题,但为什么?
在做了一点研究之后,我终于找到了一个问题的答案,我很快就会在这里提出这个问题;如何通过PHP中的Php 使用_集合解决数组问题,但为什么?,php,overloading,getter-setter,magic-methods,Php,Overloading,Getter Setter,Magic Methods,在做了一点研究之后,我终于找到了一个问题的答案,我很快就会在这里提出这个问题;如何通过PHP中的\uuu get和\uu set魔术方法处理数组?每当我试图使用$object->foo['bar']=42它似乎在默默地丢弃它 无论如何,答案很简单;\uu get方法只需通过引用返回即可。在它前面扔了一个符号后,它确实起作用了 我的问题是,为什么?我似乎不明白为什么会这样。通过引用返回的\u get如何影响\u set使用多维数组 编辑:顺便说一下,在PHP中运行PHP5.3.1P>当你从函数返回
\uuu get
和\uu set
魔术方法处理数组?每当我试图使用$object->foo['bar']=42代码>它似乎在默默地丢弃它
无论如何,答案很简单;\uu get
方法只需通过引用返回即可。在它前面扔了一个符号后,它确实起作用了
我的问题是,为什么?我似乎不明白为什么会这样。通过引用返回的\u get
如何影响\u set
使用多维数组
编辑:顺便说一下,在PHP中运行PHP5.3.1
P>当你从函数返回一个值时,你可以考虑复制一个值(除非它是一个类)。在\uuu get
的情况下,除非返回要编辑的实际内容,否则所有更改都将被复制到一个副本,然后该副本将被丢弃。在这种特殊情况下,\uu set
实际上不会被调用。如果你把发生的事情分解一下,应该会更有意义:
$tmp = $object->__get('foo');
$tmp['bar'] = 42
如果\uu get
未返回引用,则将42指定给原始对象的“条形”索引,而不是指定给原始对象副本的“条形”索引。可能更清楚:
//PHP will try to interpret this:
$object->foo['bar'] = 42
//The PHP interpreter will try to evaluate first
$object->foo
//To do this, it will call
$object->__get('foo')
// and not __get("foo['bar']"). __get() has no idea about ['bar']
//If we have get defined as &__get(), this will return $_data['foo'] element
//by reference.
//This array element has some value, like a string:
$_data['foo'] = 'value';
//Then, after __get returns, the PHP interpreter will add ['bar'] to that
//reference.
$_data['foo']['bar']
//Array element $_data['foo'] becomes an array with one key, 'bar'.
$_data['foo'] = array('bar' => null)
//That key will be assigned the value 42
$_data['foo']['bar'] = 42
//42 will be stored in $_data array because __get() returned a reference in that
//array. If __get() would return the array element by value, PHP would have to
//create a temporary variable for that element (like $tmp). Then we would make
//that variable an array with $tmp['bar'] and assign 42 to that key. As soon
//as php would continue to the next line of code, that $tmp variable would
//not be used any more and it will be garbage collected.
啊,所以在设置值的过程中,在调用\uu set
之前,调用\uu get
来检索(或检查)对象变量的存在?$object->foo['bar']=42代码>从不调用集合。在执行类似于$object->key=$value
的操作时调用Set,但在执行$object->key[$key2]=$value
时不调用Set。这是因为$object->key[$key2]
是使用\uu get
解析的,然后进行更改。所以你可以把它想象成$magic\u get\u value=$value
。在PHP5.2.x中,让uu get返回一个引用似乎没有帮助。