在JavaScript中,我知道可以简单地覆盖单个实例的类方法,但我不太确定如何在PHP中管理这个问题。这是我的第一个想法:
class Test {
public $var = "placeholder";
public function testFunc() {
echo "test";
}
}
$a = new Test();
$a->testFunc = function() {
$this->var = "overridden";
};
我的第二次尝试是使用匿名函数调用,但不幸的是会破坏对象作用域...
class Test {
public $var = "placeholder";
public $testFunc = null;
public function callAnonymTestFunc() {
$this->testFunc();
}
}
$a = new Test();
$a->testFunc = function() {
//here the object scope is gone... $this->var is not recognized anymore
$this->var = "overridden";
};
$a->callAnonymTestFunc();