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.

Example

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!'

Demo

Repl.it:



If you enjoyed this post, please consider supporting this site!