Domanda

Dopo aver fatto un po 'di ricerca, alla fine ho incontrato la risposta a una domanda che mi stava per chiedere qui comunque; Come si fa a lavorare con array attraverso i __get e __set metodi magici in PHP? Ogni volta che stavo cercando di impostare un valore usando qualcosa come $object->foo['bar'] = 42; sembrò di scartare silenziosamente.

In ogni modo, la risposta è semplice; Il metodo __get deve semplicemente restituire per riferimento. E dopo lanciare una e commerciale di fronte ad essa, abbastanza sicuro che funziona.

La mia domanda in realtà, è il motivo? Non riesco a capire perché questo sta lavorando. Come fa __get restituzione per riferimento influisce lavoro __set con array multidimensionali?

Edit: A proposito, in esecuzione di PHP 5.3.1

È stato utile?

Soluzione

In questo caso particolare, __set non è in realtà sempre chiamato. Se si spezza giù quello che succede, si dovrebbe fare un po 'più senso:

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

Se __get non ha restituito un riferimento, quindi invece di assegnare 42 al 'bar' indice dell'oggetto originale, si sta assegnerà all'indice 'bar' di un copia del oggetto originale.

Altri suggerimenti

In PHP quando si torna un valore da una funzione si può considerare di fare una copia di tale valore (a meno che non si tratta di una classe). Nel caso di __get a meno che non ritorni la cosa reale che si desidera modificare, sono fatte tutte le modifiche a una copia che viene poi scartata.

forse più chiaro:

//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.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top