你能在 PHP 数组中存储一个函数吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1499862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you store a function in a PHP array?
提问by Kirk Ouimet
e.g.:
例如:
$functions = array(
'function1' => function($echo) { echo $echo; }
);
Is this possible? What's the best alternative?
这可能吗?最好的选择是什么?
回答by Alex Barrett
The recommended way to do this is with an anonymous function:
推荐的方法是使用匿名函数:
$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'
];
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):
在古老版本的 PHP (<5.3) 中,不支持匿名函数,您可能需要求助于使用 create_function(自 PHP 7.2 起已弃用):
$functions = array(
'function1' => create_function('$echo', 'echo $echo;')
);
All of these methods are listed in the documentation under the callablepseudo-type.
所有这些方法都列在callable伪类型下的文档中。
Whichever you choose, the function can either be called directly (PHP ≥5.4) or with call_user_func/call_user_func_array:
无论您选择哪个,该函数都可以直接调用(PHP ≥5.4)或使用call_user_func/ call_user_func_array:
$functions['function1']('Hello world!');
call_user_func($functions['function1'], 'Hello world!');
回答by jave.web
Since PHP "5.3.0 Anonymous functions become available", example of usage:
由于PHP“5.3.0匿名函数可用”,使用示例:
note that this is much faster than using old create_function...
请注意,这比使用旧的要快得多create_function......
//store anonymous function in an array variable e.g. $a["my_func"]
$a = array(
"my_func" => function($param = "no parameter"){
echo "In my function. Parameter: ".$param;
}
);
//check if there is some function or method
if( is_callable( $a["my_func"] ) ) $a["my_func"]();
else echo "is not callable";
// OUTPUTS: "In my function. Parameter: no parameter"
echo "\n<br>"; //new line
if( is_callable( $a["my_func"] ) ) $a["my_func"]("Hi friend!");
else echo "is not callable";
// OUTPUTS: "In my function. Parameter: Hi friend!"
echo "\n<br>"; //new line
if( is_callable( $a["somethingElse"] ) ) $a["somethingElse"]("Something else!");
else echo "is not callable";
// OUTPUTS: "is not callable",(there is no function/method stored in $a["somethingElse"])
REFERENCES:
参考:
Anonymous function: http://cz1.php.net/manual/en/functions.anonymous.php
Test for callable: http://cz2.php.net/is_callable
回答by RibaldEddie
Warning
create_function()has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.
create_function()自 PHP 7.2.0 起,警告已被弃用。强烈建议不要依赖此功能。
To follow up on Alex Barrett's post, create_function() returns a value that you can actually use to call the function, thusly:
为了跟进 Alex Barrett 的帖子,create_function() 返回一个您可以实际用来调用该函数的值,因此:
$function = create_function('$echo', 'echo $echo;' );
$function('hello world');
回答by Stuperfied
Because I could...
因为我可以...
Expanding on Alex Barrett's post.
扩展亚历克斯·巴雷特 (Alex Barrett) 的帖子。
I will be working on further refining this idea, maybe even to something like an external static class, possibly using the '...' token to allow variable length arguments.
我将致力于进一步完善这个想法,甚至可能是一个外部静态类,可能使用 '...' 标记来允许可变长度参数。
In the following example I have used the keyword 'array' for clarity however square brackets would also be fine. The layout shown which employs an init function is intended to demonstrate organization for more complex code.
在下面的示例中,为了清楚起见,我使用了关键字“array”,但方括号也可以。所示的使用 init 函数的布局旨在演示更复杂代码的组织。
<?php
// works as per php 7.0.33
class pet {
private $constructors;
function __construct() {
$args = func_get_args();
$index = func_num_args()-1;
$this->init();
// Alex Barrett's suggested solution
// call_user_func($this->constructors[$index], $args);
// RibaldEddie's way works also
$this->constructors[$index]($args);
}
function init() {
$this->constructors = array(
function($args) { $this->__construct1($args[0]); },
function($args) { $this->__construct2($args[0], $args[1]); }
);
}
function __construct1($animal) {
echo 'Here is your new ' . $animal . '<br />';
}
function __construct2($firstName, $lastName) {
echo 'Name-<br />';
echo 'First: ' . $firstName . '<br />';
echo 'Last: ' . $lastName;
}
}
$t = new pet('Cat');
echo '<br />';
$d = new pet('Oscar', 'Wilding');
?>
Ok, refined down to one line now as...
好的,现在精简到一行,因为......
function __construct() {
$this->{'__construct' . (func_num_args()-1)}(...func_get_args());
}
Can be used to overload any function, not just constructors.
可用于重载任何函数,而不仅仅是构造函数。
回答by dhamo dharan
By using closure we can store a function in a array. Basically a closure is a function that can be created without a specified name - an anonymous function.
通过使用闭包,我们可以将函数存储在数组中。基本上,闭包是一个可以在没有指定名称的情况下创建的函数 - 一个匿名函数。
$a = 'function';
$array=array(
"a"=> call_user_func(function() use ($a) {
return $a;
})
);
var_dump($array);
回答by Constantin
<?php
$_['nice']=function(){
echo 'emulate a class';
};
$_['how']=function(){
echo ' Now you can ';
};
(function()use($_){//autorun
echo 'construct:';
($_['how'])();
($_['nice'])();
})();
//almost the same in here. i do not recomand each of them
//using array of functions or classes isn't a very high speed execution script
//when you build 70k minimum app
//IF YOU USE THESE ONLY TO TRIGGER SMALL THINGS OVER A FRAMEWORK THAT IS A GO
[
(function(){
echo 'construct 2:Now you can ';
return '';
})()
,(function(){
echo 'emulate a class';
return '';
})()
];
?>

