Using Variable Scope


As already noted, the scope of a variable is the area of your code in which it's visible. Now that we're breaking our code into functions, scope becomes a more important issue. In simple scripts, everything's in the same scope. For example, if you use a variable named $count at one point in a script:

 <?php     $count = 1;     .     .     . ?> 

Then it's the same variable when you refer to it later on as well:

 <?php     $count = 1;     .     .     .     $count = 55;     .     .     . ?> 

As your scripts get larger, of course, you might introduce a new variable named $count in the same script, forgetting that you already have one with that name, which results in conflictchanging one will change the other because they're the same as far as PHP is concerned.

That's where functions come inthey break up your code and can resolve conflicts such as this one. If you use variables in functions, their scope is restricted to those functions by default. That means that the first echo statement here will echo 5, while the second will echo 100000, because $value within the function is in the function's scope:

 $value = 5; echo "At script level, \$value = ", $value, "<BR>"; function local_scope() {     $value = 1000000;     echo "But in the function, \$value = ", $value, "<BR>"; } 

You can see how this works in Example 4-8, phpscope.php, where we're checking the same variable, $value, inside and outside a function.

Example 4-8. Checking local scope in functions, phpscope.php
 <HTML>         <HEAD>             <TITLE>                 Using local scope             </TITLE>         </HEAD>         <BODY>             <H1>Using local scope<H1>             <?php                 $value = 5;                 echo "At script level, \$value = ", $value, "<BR>";                 local_scope();                 echo "At script level again, \$value still = ", $value, "<BR>";                 function local_scope()                 {                     $value = 1000000;                     echo "But in the function, \$value = ", $value, "<BR>";                 }             ?>     </BODY> </HTML> 

The results of this script appear in Figure 4-8.

Figure 4-8. Checking function scope.


Note in particular that the local value of $value inside the function was not available outside the function. As you can see, local variables in functions are restricted to function scope.



    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