skip to Main Content

Is it possible to override a method for a single instance? e.g.

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";}

I know its abit weird but in my project a common class ("base") is part of many other classes each of which needs a slightly modified version of "base". I just need to override one method each time. Trying to avoid creating a huge number of subclasses of "base" for this purpose.

p.s. i have seen the solution you propose but it doesn’t work for me.
php version is 7.4.3

here is my code:

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

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

$a->test();

result is "internal"

2

Answers


  1. You could add a property to the class, and the print() method can check whether the property is set.

    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();
    
    Login or Signup to reply.
  2. You could declare an anonymous class on the fly:

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

    Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search