call_user_function?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Hermit TL
Forum Commoner
Posts: 69
Joined: Mon Nov 21, 2011 12:16 am

call_user_function?

Post 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?
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: call_user_function?

Post 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.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: call_user_function?

Post 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()
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: call_user_function?

Post by tr0gd0rr »

Cool! Example 5 is new to PHP 5.3
Post Reply