6.10. Calling Variable Functions

Problem

You want to call different functions depending on a variable’s value.

Solution

Use variable variables:

function eat_fruit($fruit) { print "chewing $fruit."; }

$function = 'eat_fruit';
$fruit = 'kiwi';

$function($fruit); // calls eat_fruit( )

Discussion

If you have multiple possibilities to call, use an associative array of function names:

$dispatch = array(
    'add'      => 'do_add',
    'commit'   => 'do_commit',
    'checkout' => 'do_checkout',
    'update'   => 'do_update'
);

$cmd = (isset($_REQUEST['command']) ? $_REQUEST['command'] : '');

if (array_key_exists($cmd, $dispatch)) {
    $function = $dispatch[$cmd];
    $function(); // call function
} else {
    error_log("Unknown command $cmd");
}

This code takes the command name from a request and executes that function. Note the check to see that the command is in a list of acceptable command. This prevents your code from calling whatever function was passed in from a request, such as phpinfo( ) . This makes your code more secure and allows you to easily log errors.

Another advantage is that you can map multiple commands to the same function, so you can have a long and a short name:

$dispatch = array(
    'add'      => 'do_add',
    'commit'   => 'do_commit',   'ci' => 'do_commit', 
    'checkout' => 'do_checkout', 'co' => 'do_checkout',
    'update'   => 'do_update',   'up' => 'do_update'
);

See Also

Recipe 5.5 for more on variable variables.

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.