Use this function to call other functions.

Remember the concept of variable variables? A similar thing can be done with functions and call_user_func() is a good tool to have when doing that.

The following example (with less than stellar code) calls the proper function based on input from the user.

switch( $_POST['do'] ) {
  case 'add':
  case 'sub':
  case 'mult':
  case 'div':
    $res = call_user_func( $_POST['do'],
                           floatval( $_POST['a'] ),
                           floatval( $_POST['b'] ) );
    break;
 
  default:
    die( "Can't fool me" );
}
 
echo "Result is $res";
 
function add( $a, $b ) {
  return $a + $b;
}
function sub( $a, $b ) {
  return $a - $b;
}
function mult( $a, $b ) {
  return $a * $b;
}
function div( $a, $b ) {
  return $a / $b;
}

In that case we could’ve called the function using the concept of variable functions. I think in many cases, though, using call_user_func() is clearer to read and understand the intent.

 
// Our call to call_user_func() could have been replaced
// with the following and achieved the same results
// In my opinion, however, this can be confusing to read
    $res = $_POST['do']( floatval( $_POST['a'] ),
                         floatval( $_POST['b'] ) );

You can also use this function to call class methods. For this you give the first parameter (the function name in our examples so far) as an array. The first element of this array will be either the class name or an instance of the class. The second element will be the name of the method you wish to call.

If you give the class name (as a string) it will attempt to call the method statically. If you give the instance, it will simply call the method.

The case of static methods is one where variable functions won’t work. You’ll get a parse error trying that.

class someClass {
  static public function doThis( $var ) {
    return str_rot13( $var );
  }
 
  public function doThat( $var ) {
    return strrev( $var );
  }
}
 
$c  = 'someClass';
$m1 = 'doThis';
$m2 = 'doThat';
$v  = 'Hello';
 
$res1 = call_user_func( array( $c, $m1 ), $v ); // Uryyb
$res2 = call_user_func( array( $c, $m2 ), $v ); // olleH
/*
The second call will give you a Strict Standards warning about
statically calling a non-static method but it does call the method.
$c would have to be an instance of the class to avoid that warning
*/
 
$res2 = call_user_func( array( new $c(),
                               $m2 ),
                        $v ); // olleH

Attempting to use the variable functions concept for the above simply will not work. For calling a static method, you’ll get a parse error whether it’s the class name or an instance.

// Both of these will not parse
$res1 = $c::$m1( $v );
 
$inst = new $c();
$res1 = $inst::$m1( $v );
 
// This one won't work because $c is a string, not an object
$res2 = $c->$m2( $v );
 
// This one will work!
$inst = new $c();
$res2 = $inst->$m2( $v );