Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP call_user_func vs. just calling function

Tags:

function

php

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'); 
like image 514
jay Avatar asked Oct 20 '09 17:10

jay


People also ask

Why use call_ user_ func?

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. call_user_func is not necessarily needed. You can always call a function by using variable functions: $some_func() .

What does call_ user_ func do in PHP?

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 do you call a method in PHP?

To invoke a method on an object, you simply call the object name followed by "->" and then call the method. Since it's a statement, you close it with a semicolon. When you are dealing with objects in PHP, the "->" is almost always used to access that object, whether it's a property or to call a method.


2 Answers

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.

like image 77
Kai Avatar answered Oct 08 '22 02:10

Kai


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); 
like image 23
Lucas Oman Avatar answered Oct 08 '22 01:10

Lucas Oman