如何在PHP中创建函数字典?

时间:2012-06-18 12:08:52

标签: 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);
}

但是由于函数不是PHP中的第一类对象,我无法弄清楚如何轻松地做到这一点。在PHP中有一个相当简单的方法吗?

6 个答案:

答案 0 :(得分:3)

我不明白你的意思。
如果您需要一系列函数,请执行以下操作:

$actions = array(
'doSomething'=>function(){},
'doSomething2'=>function(){}
);

您可以运行$actions['doSomething']();

的功能

当然你可以有args:

$actions = array(
'doSomething'=>function($arg1){}
);


$actions['doSomething']('value1');

答案 1 :(得分:3)

$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类型。

答案 2 :(得分:2)

您可以使用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开始)。

答案 3 :(得分:1)

// >= 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();

答案 4 :(得分:1)

如果您打算在对象上下文中使用它,则不必创建任何函数/方法字典。

您可以使用魔术方法__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

答案 5 :(得分:0)

http://php.net/manual/en/function.call-user-func.php

call_user_func将允许您从名称中执行函数作为字符串并传递参数,但我不知道这样做的性能影响。

相关问题