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

后端 未结 9 2220
星月不相逢
星月不相逢 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:15

    Without the __call solution, you can use bindTo (PHP >= 5.4), to call the method with $this bound to $me like this:

    call_user_func($me->doSomething->bindTo($me, null)); 
    

    The complete script could look like this:

    $me = new stdClass;
    // Property for proving that the method has access to the above object:
    $me->message = "I\'ve done something"; 
    $me->doSomething = function () {
        echo $this->message;
    };
    call_user_func($me->doSomething->bindTo($me)); // "I've done something"
    

    Alternatively, you could assign the bound function to a variable, and then call it without call_user_func:

    $f = $me->doSomething->bindTo($me);
    $f(); 
    

提交回复
热议问题