有一个由 (spark at limao dot com dot br) 发布的惊人代码片段的改进版本,它允许动态方法生成,并且作为 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()
);
?>