PHP覆盖单个实例的功能

mar*_*ius 5 php oop overriding

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

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

$a = new Test();

$a->testFunc = function() {
    $this->var = "overridden";
};
Run Code Online (Sandbox Code Playgroud)

我的第二次尝试是使用匿名函数调用,不幸的是杀死了对象范围。

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();
Run Code Online (Sandbox Code Playgroud)

dbf*_*dbf 6

为了全面了解您要在此处实现的目标,首先应了解所需的PHP版本,与以前的任何版本相比,PHP 7更适合OOP方法。

如果您的匿名函数绑定存在问题,则可以 PHP> = 5.4 以上的函数范围绑定到实例,例如

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

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

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

尽管您要达到的目标的方法超出了我的想象。也许您应该尝试阐明您的目标,然后我将尝试所有可能的解决方案。