将__set与数组一起使用已解决,但是为什么呢? [英] Using __set with arrays solved, but why?
问题描述
进行了一些研究,最终我找到了一个我很快将要在这里提出的问题的答案;如何通过PHP中的__get
和__set
魔术方法使用数组?每当我尝试使用$object->foo['bar'] = 42;
之类的值设置值时,它似乎都会默默丢弃它.
Having done a bit of research, I eventually came across the answer to a question I was soon to ask here anyways; How do you work with arrays via the __get
and __set
magic methods in PHP? Whenever I was trying to set a value using something like $object->foo['bar'] = 42;
it seemed to silently discard it.
无论如何,答案很简单; __get
方法仅需要通过引用返回.在前面的&"符号之后,确定它可以正常工作.
Anyways, the answer is simple; The __get
method simply needs to return by reference. And after tossing an ampersand in front of it, sure enough it works.
我的问题实际上是为什么?我似乎无法理解为什么这行得通. __get
通过引用返回如何影响__set
处理多维数组?
My question actually, is why? I can't seem to understand why this is working. How does __get
returning by reference affect __set
working with multidimensional arrays?
顺便说一句,运行PHP 5.3.1
推荐答案
在这种情况下,实际上并未调用__set
.如果您将其分解,则应该更有意义:
In this particular case, __set
is not actually getting called. If you break down what it happening, it should make a bit more sense:
$tmp = $object->__get('foo');
$tmp['bar'] = 42
如果__get
没有返回引用,则不是将42分配给原始对象的'bar'索引,而是将其分配给副本的'bar'索引原始对象.
If __get
did not return a reference, then instead of assigning 42 to the 'bar' index of the original object, you're be assigning to the 'bar' index of a copy of the original object.
这篇关于将__set与数组一起使用已解决,但是为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!