Page 1 of 1

call_user_function?

Posted: Tue Dec 20, 2011 1:42 pm
by Hermit TL
Can someone explain to me what the point of call_user_function is?

What is the difference between:

Code: Select all

function increment(&$var)
{
    $var++;
}

$a = 0;
call_user_func('increment', $a);
echo $a."\n";
and

Code: Select all

function increment($var)
{
    $var++; return($var);
}

$a = 0;
echo increment($a) ."\n";
Why would I want to use a function to call my functions when they can be called directly?

Re: call_user_function?

Posted: Tue Dec 20, 2011 1:50 pm
by tr0gd0rr
I think you are right; `call_user_func` is pretty useless. Especially since in PHP you can do `$functionName()` to call a function with the name `$functionName`.

`call_user_func_array` on the other hand is super useful because you can send a variable number of arguments.

Re: call_user_function?

Posted: Tue Dec 20, 2011 3:17 pm
by pickle
Example #5 on the documentation page gives a good example. Basically it lets you call an anonymous function - which is great if you just have some small code you want to call while in a function, ie: array_map()

Re: call_user_function?

Posted: Wed Dec 21, 2011 1:34 pm
by tr0gd0rr
Cool! Example 5 is new to PHP 5.3