PHP覆盖单个实例的函数

PHP override function of a single instance

在 javascript 中,我知道可以简单地覆盖单个实例的 class 方法,但我不太确定这在 PHP 中是如何管理的。 这是我的第一个想法:

class Test {
    public $var = "placeholder";
    public function testFunc() {
        echo "test";
    }
}

$a = new Test();

$a->testFunc = function() {
    $this->var = "overridden";
};

我的第二次尝试是使用匿名函数调用,不幸的是它杀死了 object 作用域...

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();

我会使用适用于大多数高级语言的 OOP 继承原则:

Class TestOverride extends Test {
public function callAnonymTestFunc() {
//overriden stuff
}
}

$testOverriden = new TestOverriden();
$testOverriden->callAnonymTestFunc();

为了完全理解您在这里尝试实现的目标,首先应该知道您想要的 PHP 版本,PHP 7 比任何以前的版本都更适合 OOP 方法。

如果您的匿名函数的绑定是问题所在,您可以 bind the scope of a function 从 PHP >= 5.4 到一个实例,例如

$a->testFunc = Closure::bind(function() {
    // here the object scope was gone...
    $this->var = "overridden";
}, $a);

从 PHP >= 7 开始,您可以在创建的闭包

上立即调用 bindTo
$a->testFunc = (function() {
    // here the object scope was gone...
    $this->var = "overridden";
})->bindTo($a);

虽然你的方法超出了我的想象。也许你应该试着阐明你的目标,我会尝试所有可能的解决方案。