繁体   English   中英

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

[英]How do I create a dictionary of functions in PHP?

我想要一本功能词典。 使用这个字典,我可以拥有一个接受函数名和参数数组的处理程序,并执行该函数,如果它返回任何内容,则返回它返回的值。 如果名称与现有函数不对应,则处理程序将抛出错误。

实现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'=>function(){},
'doSomething2'=>function(){}
);

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

当然你可以有args:

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


$actions['doSomething']('value1');
$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类型。

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM