[ACCEPTED]-PHP call_user_func vs. just calling function-function

Accepted answer
Score: 94

Always use the actual function name when 4 you know it.

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

Score: 33

Although you can call variable function 4 names this way:

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

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

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

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


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

Score: 13

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

$dynamicFunctionName = "barber";

call_user_func($dynamicFunctionName, 'mushroom');

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

Score: 7

With PHP 7 you can use the nicer variable-function 3 syntax everywhere. It works with static/instance 2 functions, and it can take an array of parameters. More 1 info at https://trowski.com/2015/06/20/php-callable-paradox

$ret = $callable(...$params);
Score: 5

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

  case 7:
  $func = 'run';
  $func = 'stop';

call_user_func($func, 'stuff');
Score: 3

There is no benefits calling the function 4 like that because I think it mainly used 3 to call "user" function (like plugin) because 2 editing core file is not good option. here 1 are dirty example used by Wordpress

* my_plugin.php

function myLocation($content){
  return str_replace('@', 'world', $content);

function myName($content){
  return $content."Tasikmalaya";

add_filter('the_content', 'myLocation');
add_filter('the_content', 'myName');



* core.php
* read only

$content = "hello @ my name is ";
$listFunc = array();

// store user function to array (in my_plugin.php)
function add_filter($fName, $funct)
  $listFunc[$fName]= $funct;

// execute list user defined function
function apply_filter($funct, $content)
  global $listFunc;

    foreach($listFunc as $key => $value)
      if($key == $funct)
        $content = call_user_func($listFunc[$key], $content);
  return $content;

function the_content()
  $content = apply_filter('the_content', $content);
  echo $content;




the_content(); // hello world my name is Tasikmalaya


hello world my name is Tasikmalaya
Score: 0

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

More Related questions