Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass multiple arguments to anonymous function w/ call_user_func

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);
like image 848
Kyle Decot Avatar asked Mar 16 '12 17:03

Kyle Decot


2 Answers

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

like image 139
Crashspeeder Avatar answered Nov 15 '22 15:11

Crashspeeder


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.

like image 32
Esoterica Avatar answered Nov 15 '22 16:11

Esoterica