单实例 v2 的方法覆盖

method overriding for single instance v2

是否可以覆盖单个实例的方法?例如

class test
{
    protected function print()
    {
    echo "printed from old method";
    }
}

$a= new test();
can i overrride method "print" only for object $a?
e.g. $a->test=function(){echo "printed with new method";}

我知道它有点奇怪,但在我的项目中,一个常见的 class(“base”)是许多其他 classes 的一部分,每个都需要稍微修改版本的“base”。我只需要每次重写一个方法。试图避免为此目的创建大量子class“基础”。

p.s。我已经看到你提议的 但它对我不起作用。 php 版本为 7.4.3

这是我的代码:

class nodeGroup
{
    public function test()
    {
        echo "internal";
    }
        
}

$a= new nodeGroup();
$a->test = (function() {
    echo "external";
})->bindTo($a);

$a->test();

result is "internal"

您可以在class中添加一个属性,print()方法可以检查是否设置了属性。

class test
{
    public $print_function;

    public function print()
    {
        if (isset($this->$print_function)) {
            ($this->$print_function)();
        } else {
            echo "printed from old method";
        }
    }
}

$a = new test();
$a->print_function = function() {
    echo "printed with new method";
};
$a->print();

您可以即时声明一个 anonymous class

$a = new class extends nodeGroup {
    public function test()
    {
        echo 'external';
    }
};

$a->test();  // 'external'

Demo