我正试图在一个无法修改的类中的变量上编写一个"监听器"。我正在扩展有问题的类,取消设置要侦听的属性,然后使用__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方法无法拦截变量的值。
到目前为止,这似乎是我观察变量变化的唯一方法,但我不想破解框架的核心,只想检查它的方便工作(解析器)。有没有可能做到这一点,或者用另一种方法来解决这个问题?
嗯,这很奇怪。以下代码运行良好:
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
你能告诉我这段代码是否能满足你的需求吗?如果不能,你需要什么?
HTH