RT
功能1:
$class->$func()
功能2:
//Simple callback
call_user_func($func)
//Static class method call
call_user_func(array($class,$func))
//Object method call
$class = new MyClass();
call_user_func(array($class, $func));
有区别吗?我想查看源代码(https://github.com/php/php-src)我们该怎么办?
call_user_func_array
的性能非常慢,这就是为什么在许多情况下您希望使用显式方法调用的原因。但是,有时您希望传递任意数量的作为数组传递的参数,例如
public function __call($name, $args) {
$nargs = sizeof($args);
if ($nargs == 0) {
$this->$name();
}
elseif ($nargs == 1) {
$this->$name($args[0]);
}
elseif ($nargs == 2) {
$this->$name($args[0], $args[1]);
}
#...
// you obviously can't go through $nargs = 0..10000000,
// so at some point as a last resort you use call_user_func_array
else {
call_user_func_array(array($this,$name), $args);
}
}
我会检查$nargs
到5(PHP中的函数通常不太可能接受超过5个参数,所以在大多数情况下,我们会直接调用一个方法,而不使用call_user_func_array
,这对性能有好处)
$class->method($arg)
的结果与call_user_func_array(array($class,'method'), array($arg))
相同,但第一个结果更快。