2017-03-14 4 views
0

によって:getCalculated()が計算されたプロパティを表しPHP魔法ゲッター参照することにより、価値

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; 
    } 
} 

今、私は次のことをしようとした場合:

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

$foo->calculated; // ok 

しかし、私は&__get($name)__get()署名を変更する場合、私は得る:

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

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

私はかなりの参照とゲッターで$dataの要素を返したいのですが私の__get()に値でこれは可能ですか?エラーメッセージとして

答えて

3

勧め、あなたがゲッターから変数を返す必要があります。

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

マジック!ありがとう、私はこれを試みたと思った..しかし、明らかに何とかそれを台無しに。 – Arth

関連する問題