我确信对此有一个非常简单的解释.这有什么区别:
function barber($type){
echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
Run Code Online (Sandbox Code Playgroud)
......这个(有什么好处?):
function barber($type){
echo "You wanted a $type haircut, no problem\n";
}
barber('mushroom');
barber('shave');
Run Code Online (Sandbox Code Playgroud)
Kai*_*Kai 84
知道它时,请始终使用实际的功能名称.
call_user_func 用于调用您不知道其名称的函数,但由于程序必须在运行时查找函数,因此效率低得多.
Luc*_*man 31
虽然您可以这样调用变量函数名称:
function printIt($str) { print($str); }
$funcname = 'printIt';
$funcname('Hello world!');
Run Code Online (Sandbox Code Playgroud)
在某些情况下,您不知道您传递了多少参数.考虑以下:
function someFunc() {
$args = func_get_args();
// do something
}
call_user_func_array('someFunc',array('one','two','three'));
Run Code Online (Sandbox Code Playgroud)
它分别调用静态和对象方法也很方便:
call_user_func(array('someClass','someFunc'),$arg);
call_user_func(array($myObj,'someFunc'),$arg);
Run Code Online (Sandbox Code Playgroud)
Bri*_*oth 15
该call_user_func选项是有那么你可以做这样的事情:
$dynamicFunctionName = "barber";
call_user_func($dynamicFunctionName, 'mushroom');
Run Code Online (Sandbox Code Playgroud)
其中dynamicFunctionName字符串可以更精彩,在运行时产生的.除非必须,否则不应使用call_user_func,因为它较慢.
我想这对于调用一个你事先不知道名字的函数很有用......有点像:
switch($value):
{
case 7:
$func = 'run';
break;
default:
$func = 'stop';
break;
}
call_user_func($func, 'stuff');
Run Code Online (Sandbox Code Playgroud)
使用 PHP 7,您可以在任何地方使用更好的变量函数语法。它与静态/实例函数一起工作,并且可以接受一组参数。更多信息请访问https://trowski.com/2015/06/20/php-callable-paradox
$ret = $callable(...$params);
Run Code Online (Sandbox Code Playgroud)