PHP覆盖单个实例的函数


PHP override function of a single instance

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

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

如果你的匿名函数的绑定有问题,你可以将PHP>=5.4的函数范围绑定到一个实例,例如

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

从PHP>=7开始,您可以在创建的Closure 上立即调用bindTo

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

尽管你努力实现的目标超出了我的想象。也许你应该试着澄清你的目标,我会想出所有可能的解决方案。

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

Class TestOverride extends Test {
public function callAnonymTestFunc() {
//overriden stuff
}
}
$testOverriden = new TestOverriden();
$testOverriden->callAnonymTestFunc();