PHP覆盖单个实例的函数

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

我不确定你为什么想这样做。是仅仅为了设置一个属性吗?还是有其他功能? - David Jones
2
你想在类或对象级别上覆盖吗? 如果在类级别上,您可以简单地扩展您的类并以这种方式覆盖函数。 如果在对象级别上,您可以将回调传递给构造函数。 - Schore
这将在对象级别上实现,您能否进一步解释一下“您可以将回调传递给构造函数”是什么意思?提前致谢! - marius
我发现了一个类似的线程。自定义匿名函数 - Shintiger
我们在谈论哪个PHP版本? - dbf
2个回答

11
为了全面理解你在这里想要实现什么,首先需要知道你期望的PHP版本,PHP 7比任何以前的版本更适合面向对象编程。
如果匿名函数的绑定是问题所在,你可以在PHP >= 5.4中将一个函数的作用域绑定到一个实例上,例如:bind the scope of a function
$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);

虽然你所追求的方式超出了我的想象力,也许你应该尝试澄清你的目标,我会解决所有可能的解决方案。


我想注入一个新的函数(不是覆盖现有的),但是__magic方法阻止了这样做。 - Top-Master

-6

我会使用面向对象编程中的继承原则,这在大多数高级语言中都适用:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接