call_user_func(),call_user_func_array() 是用来调用回调函数
//调用的是静态方法
<?php
namespace Foobar;
class Foo {
static public function test($param) {
print "Hello world! \$param \n";
}
}
$param = 'param'
call_user_func(__NAMESPACE__ .'\Foo::test',$param);
call_user_func(array(__NAMESPACE__ .'\Foo', 'test'), $param);
call_user_func([Foo::class, 'test'], $param);
?>
//调用非静态方法,通常要实例化
<?php
namespace Foobar;
class Foo {
public function test($param) {
print "Hello world! \$param \n";
}
}
$foo = new Foo();
$param = 'param'
call_user_func(array($foo, 'test'), $param);
//如果需要传递多个参数 :call_user_func(array($foo, 'test'), $param, $param1, $param2);
?>
call_user_func(),call_user_func_array() 主要区别,参数格式。
//call_user_func(array($foo, 'test'), [$param, $param1, $param2])这种格式会把后面数组作为一个参数传递过去
//call_user_func_array(array($foo, 'test'), [$param, $param1, $param2]) 这种格式会作为三个参数传递给回调函数,如果存在key ,忽略。
tips:一般来说
# Benchmark (2 million iterations)# Operation Seconds
# Literal function 1.218
# Variable function 1.305
# call_user_func() 2.734
# call_user_func_array() 3.386
可以看到,变量函数和普通函数调用(literal function)速度差别不大,和call_user_func相差有一倍以上,而call_user_func_array则要更慢。所以你给的代码才会尽量避免使用call_user_func_array而更倾向于使用变量函数。因为只有很少的函数会有5个以上的参数,所以上面代码里才把1到5个函数的调用用变量函数来写,而只留下小部分的函数用call_user_func_array调用,从而最大的加快程序执行速度。
其实,这些函数的效率差异不会有想象的那么大,上面的benchmark是迭代200万次的结果,如果你的程序只会调用'call_user_func_array'几千次或以下,这些差异将会非常小(大概是0.002秒左右),没必要在这些地方做优化。
参考: https://segmentfault.com/q/1010000005268876