tags:

views:

531

answers:

5

I'm sure there's a very easy explanation for this. What is the difference between this:

function barber($type){
    echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");

... and this (and what are the benefits?):

function barber($type){
    echo "You wanted a $type haircut, no problem\n";
}
barber('mushroom');
barber('shave');

Thanks in advance.

A: 

in your first example you're using function name which is a string. it might come from outside or be determined on the fly. that is, you don't know what function will need to be run at the moment of the code creation.

SilentGhost
+2  A: 

the call_user_func option is there so you can do things like:

$dynamicFunctionName = "barber";

call_user_func($dynamicFunctionName, 'mushroom');

where the dynamicFunctionName string could be more exciting and generated at run-time. You shouldn't use call_user_func unless you have to, because it is slower.

Brian Schroth
+3  A: 

Always use the actual function name when you know it.

call_user_func is for calling functions whose name you don't know ahead of time but it is much less efficient since the program has to lookup the function at runtime.

Kai
Thank-you Kai. call_user_func turned out to be exactly what I needed.
jeerose
`call_user_func` is not necessarily needed. You can always call a function by using variable functions: `$some_func()`. `call_user_func_array` is the one that is really useful.
Ionuț G. Stan
php always needs "to lookup the function at runtime"
VolkerK
A: 

I imagine it is useful for calling a function that you don't know the name of in advance... Something like:

switch($value):
{
  case 7:
  $func = 'run';
  break;
  default:
  $func = 'stop';
  break;
}

call_user_func($func, 'stuff');
pivotal
+3  A: 

Although you can call variable function names this way:

function printIt($str) { print($str); }

$funcname = 'printIt';
$funcname('Hello world!');

there are cases where you don't know how many arguments you're passing. Consider the following:

function someFunc() {
  $args = func_get_args();
  // do something
}

call_user_func_array('someFunc',array('one','two','three'));

It's also handy for calling static and object methods, respectively:

call_user_func(array('someClass','someFunc'),$arg);
call_user_func(array($myObj,'someFunc'),$arg);
Lucas Oman