6

少し調べてみると、とにかくここですぐに尋ねる質問に対する答えに出くわしました。PHPのandmagicメソッドを介し__getて配列をどのように操作しますか?__setそのようなものを使用して値を設定しようとしたときはいつでも、$object->foo['bar'] = 42;それを黙って破棄しているように見えました。

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

私の質問は、実際には、なぜですか?なぜこれが機能しているのか理解できないようです。__get参照による戻りは__set、多次元配列の操作にどのように影響しますか?

編集:ちなみに、PHP5.3.1を実行しています

4

3 に答える 3

4

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

于 2010-11-30T04:22:34.007 に答える
3

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

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

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

于 2010-11-30T04:30:00.953 に答える
2

多分もっと明確:

//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.
于 2012-07-02T06:50:44.060 に答える