我正在尝试在我无法修改的类中的变量上编写“侦听器”。我正在扩展有问题的类,取消设置我想听的属性,然后使用 __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 方法无法拦截变量的值。
到目前为止,这似乎是我可以观察变量变化的唯一方法,但我不想破解框架的核心,只检查它的方便工作(解析器)。是否有可能使这项工作或解决此问题的另一种方法?