Creating Variable Variables


That's not a typoPHP lets you create variable variables. A variable variable is one that holds the name of a variable. Here's how it works: you create a variable named, say, $apples:

 <?php     $apples = 4;         .         .         . ?> 

Then you can create a new variable, which we'll name $fruitname, that holds the name of the $apples variable:

 <?php     $apples = 4;     $fruitname = "apples";         .         .         . ?> 

Now you can refer to the value in $apples as $$fruitname:

 <?php     $apples = 4;     $fruitname = "apples";     echo "Number of apples: ", $$fruitname; ?> 

This script displays:

 Number of apples: 4 

You have to be more careful when using double-quotation interpolation, however, because PHP will have trouble with an expression such as $$fruitname in double quotes. To fix that, you use curly braces like this: ${$fruitname}.

Example 1-7, phpvariablevariables.php, shows how this works.

Example 1-7. Using variable variables
 <HTML>     <HEAD>         <TITLE>             Using variable variables         </TITLE>     </HEAD>     <BODY>         <H1>             Using variable variables         </H1>         <?php             $apples = 4;             $oranges = 3;             $fruitname = "oranges";             echo "Number of oranges: ${$fruitname} <BR>";             $fruitname = "apples";             echo "Number of apples: ${$fruitname} <BR>";         ?>     </BODY> </HTML> 

The results of this example appear in Figure 1-10.

Figure 1-10. Interpolating variable variables.


If you hadn't used the curly braces in Example 1-7, you would have gotten this result:

 Number of oranges: $oranges <BR> Number of apples: $apples <BR> 

Variable variables are important to understand, although they might not look like much more than a curiosity right now. In particular, they're very useful when you work with loops and arrays, as we'll be seeing in Chapter 3, "Handling Strings and Arrays."



    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