Wpdevstudio Wpdevstudio - 29 days ago 5
PHP Question

why should one prefer call_user_func_array over regular calling of function?

function foobar($arg, $arg2) {
echo __FUNCTION__, " got $arg and $arg2\n";
foobar('one','two'); // OUTPUTS : foobar got one and two

call_user_func_array("foobar", array("one", "two")); // // OUTPUTS : foobar got one and two

As I can see both regular one and
method both outputs same, then why should one prefer it?

In which scenario regular calling method will fail but
will not?

Can I get any such example?

Thank you

  1. You have an array with the arguments for your function which is of indeterminate length.

    $args = someFuncWhichReturnsTheArgs();
    foobar( /* put these $args here, you do not know how many there are */ );

    The alternative would be:

    switch (count($args)) {
        case 1:
        case 2:
            foobar($args[0], $args[1]);

    Which is not a solution.

The use case for this may be rare, but when you come across it you need it.