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/...
Just like normal variables, simple arrays can also be passed to a function as an argument, but in C/C++ whenever we pass an array as a function argument then it is always treated as a pointer by a function.
Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed.
The * symbol is used to pass a variable number of arguments to a function. Typically, this syntax is used to avoid the code failing when we don't know how many arguments will be sent to the function.
You need to use call_user_func_array
call_user_func_array( array($method, $function), $params);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With