Pet*_*son 5 php function-pointers
我想要一个函数字典。使用这个字典,我可以有一个处理程序,它接受一个函数名和一个参数数组,并执行该函数,如果它返回任何值,则返回它返回的值。如果名称与现有函数不对应,处理程序将抛出错误。
实现 Javascript 非常简单:
var actions = {
doSomething: function(){ /* ... */ },
doAnotherThing: function() { /* ... */ }
};
function runAction (name, args) {
if(typeof actions[name] !== "function") throw "Unrecognized function.";
return actions[name].apply(null, args);
}
Run Code Online (Sandbox Code Playgroud)
但是由于函数在 PHP 中并不是真正的一流对象,我无法弄清楚如何轻松地做到这一点。有没有一种相当简单的方法可以在 PHP 中做到这一点?
$actions = array(
'doSomething' => 'foobar',
'doAnotherThing' => array($obj, 'method'),
'doSomethingElse' => function ($arg) { ... },
...
);
if (!is_callable($actions[$name])) {
throw new Tantrum;
}
echo call_user_func_array($actions[$name], array($param1, $param2));
Run Code Online (Sandbox Code Playgroud)
您的字典可以包含任何允许的callable类型。
| 归档时间: |
|
| 查看次数: |
3291 次 |
| 最近记录: |