Creating Variable Functions


PHP also supports variable functions. That means that a variable can hold the name of a functionand you can call the function just by including parentheses after the variable. This lets you determine which function is called at run time.

NOTE

Why would you want to determine which function is called at run time? There are a number of reasons, such as implementing callback functions, where you want some code to call you backyou can pass the name of your function to some other code, and the other code can call you back when something happens (such as an Internet connection being made). You can also create dispatch tables of function names, where the correct function to call can only be determined at run time, such as when you're waiting to see what a user wants you to do.


Here's an example; say you have a function named apples:

 function apples() {     echo "In apples() now.<BR>";     echo "We have plenty of apples.<BR><BR>"; } 

To call it using function variables, just assign a variable ($function_variable in the following script) the text "apples" and then call that variable like a function:

 $function_variable = "apples"; $function_variable(); unction apples()    echo "In apples() now.<BR>";    echo "We have plenty of apples.<BR><BR>"; 

For that matter, you can pass arguments to these kinds of functions, and you can even set up default argument values, as you see in phpvarfunctions.php, Example 4-12.

Example 4-12. Using variable functions, phpvarfunctions.php
 <HTML>         <HEAD>             <TITLE>Using static variables</TITLE>         </HEAD>         <BODY>             <H1>Using static variables</H1>             <?php                 $function_variable = "apples";                 $function_variable();                 $function_variable = "oranges";                 $function_variable("In oranges() now.");                 $function_variable = "bananas";                 $function_variable("In bananas() now.");                 function apples()                 {                     echo "In apples() now.<BR>";                     echo "We have plenty of apples.<BR><BR>";                 }                 function oranges($argument)                 {                     echo "$argument <BR>";                     echo "We have plenty of oranges also.<BR><BR>";                 }                 function bananas($argument="")                 {                     echo "$argument <BR>";                     echo "Well stocked on bananas too.<BR><BR>";                 }             ?>     </BODY> </HTML> 

The results appear in Figure 4-12, where we've been able to pass data to variable functions without difficulty.

Figure 4-12. Using variable functions.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

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