8.9 Calling Functions Indirectly


You want to call function by its name , which is stored in a variable.

Technique

PHP enables you to use a variable value as the function name at call time. For example, you might have a classified -ad system that has several functions ”called process_camera() , process_computer() , process_car() , and so on ”that perform specific actions. You want to call the appropriate function depending on the type of the ad.

 <?php // Support ad type is stored in $ad_type. // Then calling the function is as simple as: */ $process_function = "process_$ad_type"; $process_function($HTTP_POST_VARS); ?> 

Comments

First, we create the full name of the function we want to call, and then we use that name instead of the static function name.

Of course, it's possible to have one function called process_ad() with a long "switch" statement inside that does appropriate processing. However, the indicated approach is more extensible and a bit cleaner. To support a new ad type, all you have to do is define a new function. (You could even define that function in a different source file and then "include" it.)



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net