Reputation: 2139
There are a few functions with different number of parameters in PHP. I have no idea which function is going to be called, but the function and its parameter is passed to the calling function as array like this
function func1($a,$b){...}
function func2($a){...}
$calls = [func1=>[arg1, arg2], func2=>[arg1]]
I need to call each function with its parameters. I don't know how to pass the parameters as distinct variables. This my code
$func_names = array_keys($calls);
$i = 0;
foreach($calls as $call){
$func_names[$i]($calls[$func_names[$i++]]);
//$func_names[$i]($call); same as above line
}
In each iteration array of arguments of each function is passed to the function not each item of the array separately. How can I solve this problem?
thanks
Upvotes: 2
Views: 1733
Reputation: 7485
<?php
function a($foo) {
echo $foo, "\n";
}
function b($bar, $baz) {
echo $bar, ' and ', $baz, "\n";
}
$calls = ['a'=>['apples'], 'b'=>['bananas','banjos']];
foreach($calls as $k => $v) $k(...$v);
Output:
apples
bananas and banjos
Upvotes: 2
Reputation: 3225
mixed call_user_func_array ( callable $callback , array $param_arr )
Example from the linked PHP manual -
<?php
function foobar($arg, $arg2) {
echo __FUNCTION__, " got $arg and $arg2\n";
}
class foo {
function bar($arg, $arg2) {
echo __METHOD__, " got $arg and $arg2\n";
}
}
// Call the foobar() function with 2 arguments
call_user_func_array("foobar", array("one", "two"));
// Call the $foo->bar() method with 2 arguments
$foo = new foo;
call_user_func_array(array($foo, "bar"), array("three", "four"));
?>
Upvotes: 2