2

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

2

2 Answers 2

2

Use call_user_func_array

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"));
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Very perfect and clean answer. Thank you
2
<?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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.