您能在PHP数组中存储函数吗?
e、 g:您能在PHP数组中存储函数吗?,php,arrays,function,Php,Arrays,Function,e、 g: 这可能吗?最好的替代方案是什么?推荐的方法是: 如果要存储已声明的函数,只需将其名称作为字符串引用即可: $functions = [ 'function1' => function ($echo) { echo $echo; } ]; 在PHP的古代版本中( 警告create_function()自PHP 7.2.0起已被弃用。强烈建议不要依赖此函数 为了继续Alex Barrett的文章,create_function()返回一个值,您可以实际使
这可能吗?最好的替代方案是什么?推荐的方法是: 如果要存储已声明的函数,只需将其名称作为字符串引用即可:
$functions = [
'function1' => function ($echo) {
echo $echo;
}
];
在PHP的古代版本中(
警告create_function()
自PHP 7.2.0起已被弃用。强烈建议不要依赖此函数
为了继续Alex Barrett的文章,create_function()返回一个值,您可以实际使用该值调用该函数,因此:
$functions['function1']('Hello world!');
call_user_func($functions['function1'], 'Hello world!');
由于PHP“5.3.0匿名函数可用”,使用示例:
注意,这比使用旧的create\u函数要快得多
//将匿名函数存储在数组变量中,例如$a[“my_func”]
$a=数组(
“my_func”=>函数($param=“no parameter”){
echo“在我的函数中。参数:”.$param;
}
);
//检查是否有某种功能或方法
如果(可调用($a[“我的函数”)$a[“我的函数”]();
else echo“不可调用”;
//输出:“在我的函数中。参数:无参数”
echo“\n
”;//新行
如果(可调用($a[“我的函数”)$a[“我的函数”(“你好朋友”);
else echo“不可调用”;
//输出:“在我的函数中。参数:Hi friend!”
echo“\n
”;//新行
如果(可调用($a[“somethingElse”)$a[“somethingElse”](“其他东西!”);
else echo“不可调用”;
//输出:“不可调用”($a[“somethingElse”]中没有存储函数/方法)
参考文献:
- 匿名函数:
- 测试是否可调用:
因为我可以
扩大亚历克斯·巴雷特的职位
我将致力于进一步完善这个想法,甚至可能是一个外部静态类,可能使用“…”标记来允许可变长度的参数
在下面的示例中,为了清晰起见,我使用了关键字“array”,但是方括号也可以。所示的布局使用了init函数,旨在演示更复杂代码的组织
//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"])
可以用于重载任何函数,而不仅仅是构造函数。通过使用闭包,我们可以将函数存储在数组中。基本上闭包是一个不需要指定名称即可创建的函数-匿名函数
function __construct() {
$this->{'__construct' . (func_num_args()-1)}(...func_get_args());
}
about call\u user\u func:Is$var=$functions[“function1”],当function1返回一个值时,坏习惯?您好@Roy。由于$functions[“functions1”]
包含一个可调用函数,将其分配给$var
将导致$var
也包含一个可调用函数。您仍然需要使用$var()调用它
获取返回值。刚刚发现一个小错误,即如果数组是类成员,则PHP5.3方法不起作用,例如:类MyClass{$functions=['function1'=>function($echo){echo$echo;}];}@ZackMorris注释应该在答案中指出,因为在类中这样做不是一个不合理的想法(在找到他的评论之前,我至少遇到过两次)从警告到PHP7.2.0,此函数已被弃用。强烈反对依赖此函数。
TL;DR-自PHP5.4:$functions=['function1'=>function($echo){echo$echo;}];
…由于PHP5.3匿名函数可用,因此从5.4开始,您可以编写[]
而不是array()
$functions['function1']('Hello world!');
call_user_func($functions['function1'], 'Hello world!');
$function = create_function('$echo', 'echo $echo;' );
$function('hello world');
//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"])
<?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');
?>
function __construct() {
$this->{'__construct' . (func_num_args()-1)}(...func_get_args());
}
$a = 'function';
$array=array(
"a"=> call_user_func(function() use ($a) {
return $a;
})
);
var_dump($array);
<?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 '';
})()
];
?>