你可以在PHP数组中存储一个函数吗?

例如:

$functions = array( 'function1' => function($echo) { echo $echo; } ); 

这可能吗? 什么是最好的select?

有几个选项。 使用create_function

 $functions = array( 'function1' => create_function('$echo', 'echo $echo;') ); 

只需将函数的名称存储为一个string(这实际上是所有的create_function都在做):

 function do_echo($echo) { echo $echo; } $functions = array( 'function1' => 'do_echo' ); 

如果您使用PHP 5.3,则可以使用匿名函数 :

 $functions = array( 'function1' => function($echo) { echo $echo; } ); 

所有这些方法都在callback伪types的文档中列出。 无论select哪一种,调用函数的推荐方法都是使用call_user_funccall_user_func_array函数。

 call_user_func($functions['function1'], 'Hello world!'); 

为了跟上Alex Barrett的post,create_function()返回一个实际可用于调用该函数的值,因此:

 $function = create_function('$echo', 'echo $echo;' ); $function('hello world'); 

由于PHP“5.3.0匿名函数可用”,用法举例:

请注意,这比使用旧的create_function快得多…

 //store anonymous function in an array variable eg $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"]) 

参考文献:

  • 匿名函数: http : //cz1.php.net/manual/en/functions.anonymous.php

  • testing可调用: http : //cz2.php.net/is_callable