Skip to content
Advertisement

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

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

//Fatal error: Call to undefined method stdClass::doSomething()

Advertisement

Answer

You can harness __call for this:

class Foo
{
    public function __call($method, $args)
    {
        if (isset($this->$method)) {
            $func = $this->$method;
            return call_user_func_array($func, $args);
        }
    }
}

$foo = new Foo();
$foo->bar = function () { echo "Hello, this function is added at runtime"; };
$foo->bar();
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement