我想要一个函数字典。有了这个字典,我可以有一个接受函数名称和参数数组的处理程序,并执行该函数,如果它返回任何内容,则返回它返回的值。如果名称与现有函数不对应,处理程序将引发错误。
实现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);
}
但是由于函数并不是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));
您的字典可以包含任何允许的callable
类型。
我不清楚你的意思。
如果您需要一系列函数,只需执行以下操作:
$actions = array(
'doSomething'=>function(){},
'doSomething2'=>function(){}
);
您可以使用$actions['doSomething']();
运行函数
当然,你可以有参数:
$actions = array(
'doSomething'=>function($arg1){}
);
$actions['doSomething']('value1');
你可以
使用PHP的__call()
:
class Dictionary {
static protected $actions = NULL;
function __call($action, $args)
{
if (!isset(self::$actions))
self::$actions = array(
'foo'=>function(){ /* ... */ },
'bar'=>function(){ /* ... */ }
);
if (array_key_exists($action, self::$actions))
return call_user_func_array(self::$actions[$action], $args);
// throw Exception
}
}
// Allows for:
$dict = new Dictionary();
$dict->foo(1,2,3);
对于静态调用,可以使用__callStatic()
(从 PHP5.3 开始)。
如果您计划在对象上下文中使用它,则不必创建任何函数/方法字典。
您可以使用魔术方法简单地在不存在的方法上引发一些错误__call()
:
class MyObject {
function __call($name, $params) {
throw new Exception('Calling object method '.__CLASS__.'::'.$name.' that is not implemented');
}
function __callStatic($name, $params) { // as of PHP 5.3. <
throw new Exception('Calling object static method '.__CLASS__.'::'.$name.' that is not implemented');
}
}
然后每隔一个类应该扩展你的MyObject
类......
http://php.net/__call
// >= PHP 5.3.0
$arrActions=array(
"doSomething"=>function(){ /* ... */ },
"doAnotherThing"=>function(){ /* ... */ }
);
$arrActions["doSomething"]();
// http://www.php.net/manual/en/functions.anonymous.php
// < PHP 5.3.0
class Actions{
private function __construct(){
}
public static function doSomething(){
}
public static function doAnotherThing(){
}
}
Actions::doSomething();
http://php.net/manual/en/function.call-user-func.php
call_user_func
将允许您从它们的名称作为字符串执行函数并传递给它们参数,但我不知道这样做对性能的影响。