你能在 PHP 数组中存储一个函数吗? [英] Can you store a function in a PHP array?
问题描述
例如:
$functions = array(
'function1' => function($echo) { echo $echo; }
);
这可能吗?最好的选择是什么?
Is this possible? What's the best alternative?
推荐答案
推荐的方法是使用 匿名函数:
$functions = [
'function1' => function ($echo) {
echo $echo;
}
];
如果你想存储一个已经声明的函数,那么你可以简单地通过名称作为字符串来引用它:
If you want to store a function that has already been declared then you can simply refer to it by name as a string:
function do_echo($echo) {
echo $echo;
}
$functions = [
'function1' => 'do_echo'
];
在古代版本的 PHP (<5.3) 中不支持匿名函数,您可能需要求助于使用 create_function
(自 PHP 7.2 起已弃用):
In ancient versions of PHP (<5.3) anonymous functions are not supported and you may need to resort to using create_function
(deprecated since PHP 7.2):
$functions = array(
'function1' => create_function('$echo', 'echo $echo;')
);
所有这些方法都列在 下的文档中callable
伪类型.
All of these methods are listed in the documentation under the callable
pseudo-type.
无论您选择哪种方式,都可以直接调用该函数 (PHP ≥5.4) 或使用 call_user_func
/call_user_func_array
:
Whichever you choose, the function can either be called directly (PHP ≥5.4) or with call_user_func
/call_user_func_array
:
$functions['function1']('Hello world!');
call_user_func($functions['function1'], 'Hello world!');
这篇关于你能在 PHP 数组中存储一个函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!