2017-03-14 2 views
0

J'ai cette classe:PHP magique getter par référence et par valeur

class Foo { 

    private $_data; 

    public function __construct(array $data){ 
     $this->_data = $data; 
    } 

    public function __get($name){ 
     $getter = 'get'.$name; 
     if(method_exists($this, $getter)){ 
      return $this->$getter(); 
     } 

     if(array_key_exists($name,$this->_data)){ 
      return $this->_data[$name]; 
     } 

     throw new Exception('Property '.get_class($this).'.'.$name.' is not available'); 
    } 

    public function getCalculated(){ 
     return null; 
    } 
} 

getCalculated() représente une propriété calculée.

Maintenant, si je les opérations suivantes:

$foo = new Foo(['related' => []]) 
$foo->related[] = 'Bar'; // Indirect modification of overloaded property has no effect 

$foo->calculated; // ok 

Mais si je change la signature __get()-&__get($name) j'obtenir:

$foo = new Foo(['related' => []]) 
$foo->related[] = 'Bar'; // ok 

$foo->calculated; // Only variables should be passed by reference 

J'aimerais assez revenir $data éléments par référence et getters en valeur dans mon __get(). Est-ce possible?

Répondre

3

Comme le message d'erreur indique, vous devez retourner une variable de votre getter:

class Foo { 

    private $_data; 

    public function __construct(array $data){ 
     $this->_data = $data; 
    } 

    public function &__get($name){ 
     $getter = 'get'.$name; 
     if(method_exists($this, $getter)){ 
      $val = $this->$getter(); // <== here we create a variable to return by ref 
      return $val; 
     } 

     if(array_key_exists($name,$this->_data)){ 
      return $this->_data[$name]; 
     } 

     throw new Exception('Property '.get_class($this).'.'.$name.' is not available'); 
    } 

    public function getCalculated(){ 
     return null; 
    } 
} 
+0

magique! Merci, je pensais que j'avais essayé ça ... mais de toute évidence, je me suis trompé. – Arth