How to pass array as multiple parameters to function?

家住魔仙堡 提交于 2019-12-01 14:15:22

问题


I have a parameters array:

$params[1] = 'param1';
$params[2] = 'param2';
$params[3] = 'param3';
...
$params[N] = 'paramN';

I have a caller to various functions:

$method->$function( $params );

How can I parse the $params array, so multiple (and unlimited) parameters can be passed to any function:

$method->$function( $params[1], $params[2], ..., $params[N] );

The idea is to utilize the url rewrite like this:

http://domain.com/class/method/parameter/parameter/parameter/...


回答1:


You need to use call_user_func_array

call_user_func_array( array($method, $function), $params);



回答2:


As of PHP 5.6 you can use argument unpacking:

function add($a, $b, $c) {
    return $a + $b + $c;
}

$numbers = [1, 2, 3];
echo add(...$numbers);


来源:https://stackoverflow.com/questions/2720318/how-to-pass-array-as-multiple-parameters-to-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!