Home » Php » php – Pass multiple arguments to anonymous function w/ call_user_func

php – Pass multiple arguments to anonymous function w/ call_user_func

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have an array of arguments that I want to pass to a function via call_user_func. The following code will currently give the error: Missing argument 2 for Closure. How can this be rewritten to work properly?

$args = array('foo', 'bar');
call_user_func(function($arg1, $arg2) {}, $args);
How to&Answers:

Try call_user_func_array() if you’re looking to pass an array of parameters.

Answer:

Know this has been answered. However the following also works fine.

Exec between 100,000 accesses


1.006599 : call_user_func($func, $value)

1.193323 : call_user_func((array($object, $func), $value)

1.232891 : call_user_func_array($func, array($value))

1.309725 : call_user_func_array((array($object, $func), array($value)

If you need to use call_user_func :

call_user_func(
    $function,
        $arg1,$arg2
);

If you need to use call_user_func_array :

call_user_func_array(
    $function,
        array($arg1,$arg2)
);

By design both can pass in arrays regardless. However, also by design one may be more required for use, than the other. It all depends on what it is being used for. A simplistic array set passes just fine and faster, in call_user_func.

Answer:

Either pass them one by one, or have the callback function accept an array as an argument and do the parsing internally.