PHP 魔术 getter 按引用和按值
PHP magic getter by reference and by value
我有这个class:
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()
表示计算得到的属性.
现在,如果我尝试以下操作:
$foo = new Foo(['related' => []])
$foo->related[] = 'Bar'; // Indirect modification of overloaded property has no effect
$foo->calculated; // ok
但是如果我将 __get()
签名更改为 &__get($name)
我得到:
$foo = new Foo(['related' => []])
$foo->related[] = 'Bar'; // ok
$foo->calculated; // Only variables should be passed by reference
我很想 return $data
在我的 __get()
中通过引用和值获取元素。这可能吗?
如错误消息所示,您需要 return 来自 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;
}
}
我有这个class:
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()
表示计算得到的属性.
现在,如果我尝试以下操作:
$foo = new Foo(['related' => []])
$foo->related[] = 'Bar'; // Indirect modification of overloaded property has no effect
$foo->calculated; // ok
但是如果我将 __get()
签名更改为 &__get($name)
我得到:
$foo = new Foo(['related' => []])
$foo->related[] = 'Bar'; // ok
$foo->calculated; // Only variables should be passed by reference
我很想 return $data
在我的 __get()
中通过引用和值获取元素。这可能吗?
如错误消息所示,您需要 return 来自 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;
}
}