call_user_func_array vs $ controller-> $ method($ params)?

时间:2011-03-20 14:36:01

标签: php

我在我的代码中使用它:

 call_user_func_array ( array ($controller, $method ), $this->params );

但我发现下面的代码做了同样的事情:

 $controller->$method($this->params);

两个版本之间有什么区别吗?

谢谢

Adam Ramadhan

4 个答案:

答案 0 :(得分:5)

他们的工作方式相似。唯一显着的区别是$controller->$nonexistant()会产生致命错误。如果call_user_func_array失败,只有E_WARNING $method不存在。

有趣的事实。如果你的$ controller有一个闭包$方法,那么你实际上必须结合两种方法:

call_user_func_array ( $controller->$method, $this->params );

答案 1 :(得分:5)

它们不一样。

如果$methodshowAction$this->paramsarray(2, 'some-slug'),则第一次调用将相当于:

$controller->showAction(2, 'some-slug');

而第二个是:

$controller->showAction(array(2, 'some-slug'));

您要使用哪一个取决于系统其余部分的工作方式(特别是您的控制器)。我个人可能会选择第一个。

答案 2 :(得分:0)

他们正在做同样的事情,但第二种形式更短,更清晰,更快。喜欢它。

答案 3 :(得分:0)

$controller->$method($this->params);

在这种情况下,您的函数将获得一个参数数组,谁知道它们可以有多少个,谁知道$ params [0]内部可以是什么

function myaction($params){
    echo $params[0].$params[1].$params[2];
    }

在另一种情况下,您可以从参数数组中获取确切的变量

call_user_func_array ( array ($controller, $method ), $this->params );

主要例子 您有

之类的网址
http://example.com/newsShow/150/10-20-2018

或类似的

http://example.com/newsShow/150/10-20-2018/someotherthings/that/user/can/type

在两种情况下,您只会得到所需的东西

call_user_func_array ( array ($controller, myaction ), $this->params );

function myaction($newsid,$newsdate){
    echo $newsid; // will be 150
    echo $newsdate; // will be 10-20-2018
    }