首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP &$ call_user_func ->$func()

PHP &$ call_user_func ->$func()
EN

Stack Overflow用户
提问于 2012-09-07 11:59:54
回答 1查看 9.3K关注 0票数 3

RT

功能1:

代码语言:javascript
复制
$class->$func()

功能2:

代码语言:javascript
复制
//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),我们该怎么办?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-07 12:07:08

call_user_func_array在性能方面非常慢,这就是为什么在很多情况下你想使用显式的方法调用。但是,有时您希望传递作为数组传递的任意数量的参数,例如

代码语言:javascript
复制
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))相同,但第一个更快。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12311532

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档