重写同一属性上__get和__set的递归限制


Override recursion limits for __get and __set on the same property

是否有方法覆盖相同属性上__get__set的递归限制。我希望能够以不同于第一次进入的方式处理第二次再入。

这个代码示例并不实用,但却是最简单的说明。

 class Foo {
     public function __set($name,$value){
         print "$name entered'n";
         this->$name = $value; // want it to recurse here
     }
 }
$a = new Foo();
$a->baz = "derp";
print $a->baz;
// should get (cannot test at the moment)
// baz entered
// derp  <- you get derp because the current php implementation creates an instance variable from the second call to __set

我的互联网坏了,所以我在手机上打字,所以很可能是打字错误。

使用该语法无法做到这一点。直接调用__set即可,例如:

class Foo {
     public function __set($name, $value) {
         print "$name entered'n";
         $this->__set($name, $value);
     }
}

我知道这是一个老问题,但我认为这正是你真正想要的。

<?php
class Foo {
    private $_data = array();
    public function __set($name,$value){
        print "$name entered'n";
        $this->_data[$name] = $value;
    }
    public function __get($name){
        if(array_key_exists($name, $this->_data)){
            return $this->_data[$name];
        } else {
            return false;
        }
    }
 }
$a = new Foo();
$a->baz = "derp";
print $a->baz;
?>

http://phpfiddle.org/main/code/4h0-an7