How to add a new method to a php object on the fly?

后端 未结 9 2235
星月不相逢
星月不相逢 2020-11-28 04:03

How do I add a new method to an object \"on the fly\"?

$me= new stdClass;
$me->doSomething=function ()
 {
    echo \'I\\\'ve done something\';
 };
$me->         


        
9条回答
  •  再見小時候
    2020-11-28 04:24

    Using simply __call in order to allow adding new methods at runtime has the major drawback that those methods cannot use the $this instance reference. Everything work great, till the added methods don't use $this in the code.

    class AnObj extends stdClass
    {
        public function __call($closure, $args)
        {
            return call_user_func_array($this->{$closure}, $args);
        }
     }
     $a=new AnObj();
     $a->color = "red";
     $a->sayhello = function(){ echo "hello!";};
     $a->printmycolor = function(){ echo $this->color;};
     $a->sayhello();//output: "hello!"
     $a->printmycolor();//ERROR: Undefined variable $this
    

    In order to solve this problem you can rewrite the pattern in this way

    class AnObj extends stdClass
    {
        public function __call($closure, $args)
        {
            return call_user_func_array($this->{$closure}->bindTo($this),$args);
        }
    
        public function __toString()
        {
            return call_user_func($this->{"__toString"}->bindTo($this));
        }
    }
    

    In this way you can add new methods that can use the instance reference

    $a=new AnObj();
    $a->color="red";
    $a->sayhello = function(){ echo "hello!";};
    $a->printmycolor = function(){ echo $this->color;};
    $a->sayhello();//output: "hello!"
    $a->printmycolor();//output: "red"
    

提交回复
热议问题