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),我们该怎么办?
发布于 2012-09-07 12:07:08
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))相同,但第一个更快。
https://stackoverflow.com/questions/12311532
复制相似问题