Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 call_user_func_array method both outputs same, then why should one prefer it?

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

Can I get any such example?

Thank you

like image 537
Prince Singh Avatar asked Aug 30 '13 06:08

Prince Singh


People also ask

What is the use of Call_user_func_array?

The call_user_func() is an inbuilt function in PHP which is used to call the callback given by the first parameter and passes the remaining parameters as argument. It is used to call the user-defined functions.

How to call function in array in PHP?

To apply a function to every item in an array, use array_map() . This will return a new array. $array = array(1,2,3,4,5); //each array item is iterated over and gets stored in the function parameter. $newArray = array_map(function($item) { return $item + 1; }, $array);


1 Answers

  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:         foobar($args[0]);         break;     case 2:         foobar($args[0], $args[1]);         break;     ... } 

    Which is not a solution.

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

like image 134
deceze Avatar answered Oct 11 '22 14:10

deceze