这是允许动态生成方法并作为StdClass通用扩展的精彩代码片段的改进版本。
这个版本更快,针对闭包进行了优化,并且只适用于闭包。兼容版本:>= 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);
}
}
?>
使用方法示例
<?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()
);
?>
这将接受数组、字符串和闭包,但由于使用了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);
}
}
?>
使用方法示例
<?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()
);
?>