如何从扩展类中的父对象中删除属性?

时间:2013-02-07 05:53:17

标签: php inheritance unset

我试图在一个我无法修改的类中的变量上写一个“监听器”。我正在扩展有问题的类,取消设置我想要监听的属性,然后使用__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方法无法拦截变量的值。

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

1 个答案:

答案 0 :(得分:1)

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

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