Using Static Variables


It's important to know that local variables in functions are reset to their default values every time the function is called, unless you take special steps. For example, say you had a counter function that incremented a count held in an internal variable each time you called it, as in Example 4-10, phpstatic.php.

Example 4-10. The problem with local variables, phpstatic.php
 <HTML>         <HEAD>             <TITLE>Using static variables</TITLE>         </HEAD>         <BODY>             <H1>Using static variables</H1>             <?php                echo "Current count: ", track_count(), "<BR>";                echo "Current count: ", track_count(), "<BR>";                echo "Current count: ", track_count(), "<BR>";                echo "Current count: ", track_count(), "<BR>";                echo "Current count: ", track_count(), "<BR>";                function track_count()                {                    $counter = 0;                    $counter++;                    return $counter;                }             ?>     </BODY> </HTML> 

Unfortunately, the $count local variable is set to 0 each time the function is called and then incremented to 1, so instead of incrementing the count, all you see each time this function is called is 1, as shown in Figure 4-10.

Figure 4-10. The non-working counter example.


The solution is to declare $count as static, which means it will retain its value between function calls. You can see this fixjust a single word!at work in Example 4-11, phgpstatic.php.

Example 4-11. Using global scope data in functions, phgpstatic.php
 <HTML>         <HEAD>             <TITLE>Using static variables</TITLE>         </HEAD>         <BODY>             <H1>Using static variables</H1>             <?php                echo "Current count: ", track_count(), "<BR>";                echo "Current count: ", track_count(), "<BR>";                echo "Current count: ", track_count(), "<BR>";                echo "Current count: ", track_count(), "<BR>";                echo "Current count: ", track_count(), "<BR>";                function track_count()                {                    static $counter = 0;                    $counter++;                    return $counter;                }             ?>     </BODY> </HTML> 

Now $count retains its values between function calls, as you see in Figure 4-11.

Figure 4-11. The working counter example.




    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