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

With PHP 7 you can use anonymous classes, which eliminates the stdClass limitation.

$myObject = new class {
    public function myFunction(){}
};

$myObject->myFunction();

PHP RFC: Anonymous Classes


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

Tags:

Php

Methods