質問

少し研究をした後、私は最終的に、とにかくここですぐに尋ねる質問に対する答えに出くわしました。介して配列をどのように使用しますか __get__set PHPの魔法の方法?のようなものを使用して値を設定しようとしているときはいつでも $object->foo['bar'] = 42; それは静かにそれを捨てるように見えました。

とにかく、答えは簡単です。 __get メソッドは単に参照により返す必要があります。そして、その前にアンパサンドを投げた後、十分に機能します。

私の質問は実際に、なぜですか?なぜこれが機能しているのか理解できないようです。どうやって __get 参照によって返される影響 __set 多次元アレイを使用していますか?

編集:ちなみに、PHP 5.3.1を実行します

役に立ちましたか?

解決

この特定のケースでは、 __set 実際には呼ばれていません。あなたがそれが何が起こっているかを分解した場合、それはもう少し理にかなっているはずです:

$tmp = $object->__get('foo');
$tmp['bar'] = 42

もしも __get 参照を返さなかった後、42を元のオブジェクトの「bar」インデックスに割り当てる代わりに、aの「bar」インデックスに割り当てます コピー 元のオブジェクトの。

他のヒント

PHPでは、関数から値を返すと、その値のコピーを作成することを検討できます(クラスでない限り)。の場合 __get 編集する実際のものを返しない限り、すべての変更はコピーに行われ、その後破棄されます。

多分もっと明確:

//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.
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top