单个实例的PHP覆盖功能 [英] PHP override function of a single instance
问题描述
在 javascript 中,我知道可以简单地覆盖单个实例的类方法,但我不太确定这是如何在 PHP 中管理的.这是我的第一个想法:
In javascript i know it is possible to simply override a class-method of a single instance but I am not quite sure how this is managable in PHP. Here is my first idea:
class Test {
public $var = "placeholder";
public function testFunc() {
echo "test";
}
}
$a = new Test();
$a->testFunc = function() {
$this->var = "overridden";
};
我的第二次尝试是匿名函数调用,不幸的是它杀死了对象作用域...
My second attempt was with anonymous function calls which unfortunately kills the object scope...
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 方法版本.
In order to fully understand what you are trying to achieve here, your desired PHP version should be known first, PHP 7 is more ideal for OOP approaches than any previous version.
如果你的匿名函数的绑定有问题,你可以绑定a的作用域函数 PHP >= 5.4 到一个实例,例如
If the binding of your anonymous function is the problem, you can bind the scope of a function as of PHP >= 5.4 to an instance, e.g.
$a->testFunc = Closure::bind(function() {
// here the object scope was gone...
$this->var = "overridden";
}, $a);
从 PHP >= 7 开始,您可以在创建的闭包上立即调用 bindTo
As of PHP >= 7 you can call bindTo
immediately on the created Closure
$a->testFunc = (function() {
// here the object scope was gone...
$this->var = "overridden";
})->bindTo($a);
尽管您尝试实现的方法超出了我的想象.也许你应该试着澄清你的目标,我会找出所有可能的解决方案.
Though your approach of what you are trying to achieve is beyond my imagination. Maybe you should try to clarify your goal and I'll workout all possible solutions.
这篇关于单个实例的PHP覆盖功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!