Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata