There comes improved version of amazing snippet posted by (spark at limao dot com dot br) which allows dynamic methods generations and works as versatile extension of StdClass:
This one is faster, optimised for closures, and will work only with closures. Compatible: >= PHP 5.6
<?php
class Dynamic extends \stdClass
{
public function __call($key, $params)
{
if ( ! isset($this->{$key})) {
throw new Exception("Call to undefined method " . __CLASS__ . "::" . $key . "()");
}
return $this->{$key}->__invoke(... $params);
}
}
?>
Usage examples:
<?php
$dynamic = new Dynamic();
$dynamic->anotherMethod = function () {
echo "Hey there";
};
$dynamic->randomInt = function ($min, $max) {
return mt_rand($min, $max); };
var_dump(
$dynamic->randomInt(1, 11),
$dynamic->anotherMethod()
);
?>
This will accept arrays, strings and Closures but is a bit slower due to call_user_func_array
<?php
class Dynamic extends \stdClass
{
public function __call($key, $params)
{
if ( ! isset($this->{$key})) {
throw new Exception("Call to undefined method " . __CLASS__ . "::" . $key . "()");
}
return call_user_func_array($this->{$key}, $params);
}
}
?>
Usage examples:
<?php
$dynamic = new Dynamic();
$dynamic->myMethod = "thatFunction";
$dynamic->hisMethod = array($dynamic, "randomInt");
$dynamic->newMethod = array(SomeClass, "staticMethod");
$dynamic->anotherMethod = function () {
echo "Hey there";
};
$dynamic->randomInt = function ($min, $max) {
return mt_rand($min, $max); };
var_dump(
$dynamic->randomInt(1, 11),
$dynamic->anotherMethod(),
$dynamic->hisMethod()
);
?>