开发者

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

I 'm using this in my code:

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

but I found out that the code below does the same thing:

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

Is there any difference between the two versions?

Thanks

Ad开发者_运维技巧am Ramadhan


They are not the same.

If $method is showAction and $this->params is array(2, 'some-slug'), then the first call would be equivalent to:

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

Whereas the second would be:

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

Which one you want to use depends on how the rest of your system works (your controllers in particular). I personally would probably go with the first.


They work alike. The only significant difference is that $controller->$nonexistant() would generate a fatal error. While call_user_func_array fails with just an E_WARNING should $method not exist.

Fun fact. Should your $controller harbor a closure $method, then you would actually have to combine both approaches:

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


They are doing the same thing, but the second form is shorter, clearer, and faster. Prefer it.


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

In this case your function will get an array of params and who know how many of them can be and who know what inside $params[0] can be

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

In another case you can get exactly a variable from array of params

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

Prime example You have URL like

http://example.com/newsShow/150/10-20-2018

or like that

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

in both case you will get only what you need to get

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
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜