3

我正在尝试在我无法修改的类中的变量上编写“侦听器”。我正在扩展有问题的类,取消设置我想听的属性,然后使用 __set 拦截对该变量的写入。那时我会与以前的版本进行比较,并报告是否有变化。

class A {
    var $variable;

    ...
}

class B extends A {
    var $new_variable

    function __construct() {
        parent::__construct();
        unset($this->variable);
    }

    function __set($thing, $data) {
        if ($thing == 'variable') {
            // Report change
            // Set $new_variable so we can use __get on it
        }
    }

    public function __get($var) {
        if (isset($this->$var)) {
            // Get as normal.
            return $this->$var;
        } elseif ($var == 'variable' && isset($this->new_variable)) {
            return $this->new_variable;
        }
    }

    ...
}

如果我直接修改相关类而不是通过扩展类,删除变量的声明并引入 setter 和 getter 方法,则此方法有效。问题是当我使用上面显示的模式时,unset() 调用似乎并没有真正删除从父类继承的变量,从而导致 __set 方法无法拦截变量的值。

到目前为止,这似乎是我可以观察变量变化的唯一方法,但我不想破解框架的核心,只检查它的方便工作(解析器)。是否有可能使这项工作或解决此问题的另一种方法?

4

1 回答 1

2

嗯,这很奇怪。以下代码工作正常:

class A 
{
    var $variable;
}

class B extends A 
{
    var $new_variable;

    function __construct() 
    {
        unset($this->variable);
    }

    function __set($thing, $data) 
    {
        if ($thing == 'variable') 
        {
        echo "\nThe variable value is '" . $data . "'\n";
        }
    }
}

$b = new B();
$b->variable = 'Intercepted'; //Output: The variable value is 'Intercepted'
$b->new_variable = 'Not intercepted'; // No output

你能告诉我这段代码是否满足你的需要,如果没有,你需要什么?

高温高压

于 2013-02-07T15:00:03.187 回答