Chapter 10 Exercises
Exercise 5: Understanding Variable Scope
The concept of variable scope was not introduced in Chapter 2, Variables, because without an understanding of functions, scope makes little sense. Now that you have a reasonable familiarity with functions, we will revisit the topic of variables and discuss in some detail just how variables and functions work together.
As you saw in Exercise 2: 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. In contrast, environment variables (such as $_SERVER[‘PHP_SELF’]) exist throughout the server.
Functions, though, create a new level of scope. Function variables—the arguments of a function as well as any variables defined within the function—exist only within that function and are not accessible outside of it (that is, they are local variables with local scope). Likewise, a variable from outside 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:
As long as $variable exists outside of the function, it will also have the same value within the function.
This leads to another issue 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). Let’s go over this more explicitly.
Frequently, you will use a function call line like this one:
The function [here, function_name ($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 is also $value1 [so the function-creation line reads function_name($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. One has a scope within the function, and the other has a scope outside of it.
So, you do not have to come up with different names. You can use the exact same name in the function and the call line for the sake of convenience (it becomes 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 this exercise you will rework the calculator.php script using the global statement.
To use a global statement:
Script 10-5: The function in this script can use the $tax variable—even though it hasn’t been passed to the function—thanks to the global statement.
- To begin, using Synapse to connect to the production server, open calculator.php (Script 10-4) in Brackets, if it is not already open.
- Before the function definition, add the following (Script 10-5):
Here you create a $tax variable with a set value (8.75) to be used in the cost calculations. It is assigned a value outside of the function because it will be used later in the main body of the script. - Within the function definition, add a global statement:
This statement tells the function to incorporate the same $tax variable as the one that exists outside of the function. - Before the $total in the function is formatted, recalculate the value using the tax rate:
To add the tax to the total value, start by dividing the tax by 100, to create a percentage. Then add 1 to this value to get a multiplier. This result is then multiplied by the total to come up with the new, final total.
Notice that you use a $taxrate variable (based on $tax) to perform these calculations. This is because you will print out the value of $tax later, and any changes to it here will be reflected (because it is a global variable). - Alter the main print() statement so that it prints the tax rate:
The $tax variable defined at the beginning of the script is printed out at the end. If you didn't use the $taxrate variable within the function and made the alterations to the global $tax instead, those calculations would be reflected in the value printed here. - Save the script, again as calculator.php.
- Switch over to your browser, and test the file there (Figures 10-9 and 10-10). Ensure that you are looking at the production server version of the file, having refreshed to see the latest iteration.
Figure 10-9: Run the form again...
Figure 10-10: ...and the calculation now makes use of a global $tax variable.
- If your file needs editing, you can continue editing and saving your changes in Brackets, then just switching to your browser and refreshing the page. Since you have opened this file straight from the production server using Synapse, your changes will be applied right on the production server. This means that you don’t need to use FTP.
- Constants and the superglobal arrays ($_GET, $_POST, $_COOKIE, and $_SESSION) have the added benefit that they are always available inside functions without requiring the global statement (which is why they are called superglobal).
- When it comes to naming conventions for function arguments, there are different schools of thought. On the one hand, using the same name in the function as a variable outside of the function means it is easy to remember how values match up. On the other hand, using generic argument names in your function means it is less script-specific. You can also use a hybrid method by appending a lowercase f to the beginning of function names, such as $f_quantity and $f_tax. Some programmers identify global variables as $g_variable. Again, the key is to remain consistent with your naming policy.