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->
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();