PHP dynamic method

You can dynamically create PHP methods using what they call “overloading”.

The magic class method __call() allows undeclared methods to be invoked in the object context.


Given a class with the magic method __call():

class MyClass
    public function __call(string $method, array $arguments)
        return call_user_func_array($this->$method, $arguments);

And the class is instantiated:

$instance = new MyClass();

You can dynamically set and call a method on the object:

$instance->sayHello = function ($name) {
    return "Hello, $name!";
$instance->sayHello('world'); // 'Hello, world!'


Please support this site and join our Discord!