Home > Software engineering >  How can PHP class methods be overridden during instantiation
How can PHP class methods be overridden during instantiation

Time:03-03

class c1 {
  public function fun(){
    var_dump('fun');
  }
}

$n = new c1();
$n->fun = function(){
  var_dump('222');
};

$n->fun();//fun This is not the result I want

It can be implemented in JS. I know that extensions can inherit it, but I still like the way of JS

CodePudding user response:

PHP does not support this. The language automatically evaluates $instance->fn() as a method call.

The only possible workaround is to extract the automatic property and call it separately.

($n->fun)();

However if there is no fun property defined, it will not fallback to the method and you will get the following errors

Warning: Undefined property: c1::$fun

Fatal error: Uncaught Error: Value of type null is not callable

Demo ~ https://3v4l.org/fcBo1


In general, I would not recommend what you're trying to do. I can't even think of a relevant usage for this.

CodePudding user response:

Maybe use callback can do it:

class c1 {
    private $callback;
    public function setFun($callback)
    {
        $this->callback = $callback;
    }
    public function fun()
    {
        ($this->callback)();
    }
}

$n = new c1();
$n->setFun(function () {
    var_dump('this callback');
});

$n->fun();

Demo

  •  Tags:  
  • php
  • Related