0

有没有办法覆盖同一属性的__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

我的互联网中断了,所以我在手机上打字,所以很可能有错别字。

4

2 回答 2

0

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

<?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

于 2013-07-30T11:20:27.953 回答
0

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

class Foo {
     public function __set($name, $value) {
         print "$name entered\n";

         $this->__set($name, $value);
     }
}
于 2012-08-21T14:59:22.527 回答