Variables and Functions

I l @ ve RuBoard

Variables and Functions

I did not introduce the concept of variable scope in Chapter 2, Variables , because without an understanding of functions, scope makes little sense. Now that you have a reasonable familiarity with functions, I'll revisit the topic of variables and discuss in some detail how exactly variables and functions work together.

Variable scope and the global statement

As you saw in the second section of this chapter, Creating and Calling Functions that Take Arguments , you can send variables to a function by passing them as arguments. However, you can also call a variable from within a function using the global statement. This is possible because of variable scope. The scope of a variable is essentially the realm in which it exists. By default, the variables you write in a script exist for the life of that script. Conversely, environment variables (such as $PHP_SELF) exist throughout the server.

Functions, though, create a new level of scope. Function variablesthe arguments of a function as well as any variables defined within the functiononly exist within that function and are not accessible outside of it (i.e. they are local variables with local scope). Likewise a variable from outside of a function can only be referenced by passing it to the function as an argument or by using the global statement. The global statement roughly means "I want this variable within the function to be the same as it is outside of the function." In other words, the global statement turns a local variable with local scope into a global variable with global scope. Any changes made to the variable within the function are also passed on to the variable when it is outside of the function ( assuming the function is called, that is), without using the return command. The syntax of the global statement is as follows :

 function FunctionName ($Argument) {    global $Variable; statement(s); } 

As long as $Variable exists outside of the function, it will also have the same value within the function. This leads to a parallel topic regarding functions and variables: because of variable scope, a variable within a function is a different entity (perhaps with a different value) than a variable outside of the function, even if the two variables use the exact same name (and assuming you do not use the global statement within the function). I'll go over this more explicitly.

Frequently you use a function call line like FunctionName ($Value1) ; in which case the function (here, FunctionName ($Argument1) ) then equates the value of $Argument1 to that of $Value1, so their values are the same but their names are different. However, if the name of the argument in the function was also $Value1 (so the function creation line reads FunctionName ($Value1) ), the $Value1 variable within the function assumes the same value as the original $Value1 outside of the function but they are still two separate variables. The one has a scope within the function and the other outside of it. For this reason, I have been careful, when writing functions, to use different variable names in the function defining line than I did in the function call line in order to avoid confusion.

I mention this topic because you do not actually have to come up with different names. You could use the exact same name in the function and the call line for convenience sake (it becomes very easy to remember what arguments are passed that way), but remember that they are not the same variable. What happens to a variable's value within a function stays within the function, unless you use the global statement, which does make the two variables the same.

In order to better understand this concept, you'll rework the numbers .php script using the global statement.

To use the global statement:

  1. Open numbers.php in your text editor (Script 9.6).

  2. Remove the $Price and $TaxRate arguments from the CalculateTotal function (Script 9.7) so that line 2 now looks like so:

    Figure 9.7. Since the $Cost and $Tax values are required by the CalculateTotal function, that can be brought in just as easily using the global statement. When making this change, remember to no longer pass them as arguments, which could confuse the programmer and create peculiar errors.

    graphics/09sc07.jpg

    graphics/09sc07a.jpg

     function CalculateTotal ($HowMany,  $Savings) { 

    The $Price and $TaxRate variables will be brought into the function as $Cost and $Tax using the global statement so it will no longer be necessary to pass them as arguments.

  3. Add two global statements:

     global $Cost; global $Tax; 

    These two statements tell the function to incorporate the exact same $Cost and $Tax variables as the ones that exist outside of the function.

  4. Edit the rest of the function using $Cost in place of $Price, $Tax instead of $TaxRate, and $TotalCost in lieu of $TheCost:

     $Tax++; // $Tax is now worth 1.06.     $TotalCost = ($Cost * $HowMany);     if ( ($TotalCost < 50) AND      ($Savings) ) {         print ("Your $$Savings will          not apply because the          total value of the sale          is under !\n<P>");     }     if ($TotalCost >= 50) {         $TotalCost = $TotalCost -          $Savings;     }     $TotalCost = $TotalCost * $Tax;     return $TotalCost; 

    Since the function is now using different variable names, the calculations must be changed accordingly . To get an understanding of variable scope, I've also changed the $TheCost variable to be called $TotalCost. Remember that the $TotalCost variable within the function is a different variable than the same one referred to outside of the function, even though, in the end they will both have the same value.

  5. Further down the script, after the line $Tax = 0.06; (line 29), print out the current value of the variable to monitor how it changes over the course of the page.

     print ("The tax value is currently  $$Tax .\n<P>"); 

    To demonstrate that the global variable brings the $Tax variable into the function and that any changes made within the function apply globally, you'll print out the value of $Tax before and after the function is called.


    Figure .

    graphics/09sc07.jpg


  6. Change the CalculateTotal() function call so that $Tax and $Cost are no longer passed as arguments.

     $TotalCost = CalculateTotal  ($Quantity, $Discount); 

    Since the function now only takes two arguments, passing four arguments as the script used to do would cause a error.

  7. Once again print out the value of $Tax.

     print ("After calling the function,  the tax value is now $$Tax .}  n<P>"); 

    Without the global statement, the value printed here and the value printed above would be the same. Since the global $Tax was modified in the function, though, you will see different values printed.

  8. Save your script, upload it to the server, and test it in your Web browser (Figure 9.5). Remember to send the script a Quantity value (and a Discount value, if you want)by appending it to the URL or via an HTML form.

    Figure 9.5. Because the $Tax variable within the function is the same variable as the similarly-named $Tax variable outside of the function (on account of the global statement), every change made to its value within the function is applied universally .

    graphics/09fig05.jpg

I l @ ve RuBoard


PHP for the World Wide Web (Visual QuickStart Guide)
PHP for the World Wide Web (Visual QuickStart Guide)
ISBN: 0201727870
EAN: 2147483647
Year: 2001
Pages: 116
Authors: Larry Ullman

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