Book HomePHP CookbookSearch this book

6.11. Calling Variable Functions

6.11.1. Problem

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

6.11.2. Solution

Use variable variables:

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

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

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

6.11.3. 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'
);

6.11.4. See Also

Recipe 5.5 for more on variable variables.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.