Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
This chapter is from the book

Variable Scope

Variable scope is a tricky but important concept. Every variable in PHP has a scope to it, which is to say a realm in which the variable (and therefore its value) can be accessed. As a rule of thumb, every variable has the scope of the page in which it resides. In other words, you can refer to a variable anywhere within a script once you've defined it (set its value). Assuming your PHP configuration has register_globals turned on, your form values can be accessed anywhere within the handling page.

Since included files act as if they were part of the original (including) script, variables defined before the include line are available to the included file. Further, variables defined within the included file are available to the parent (including) script after the include line.

All of this becomes murkier when using your own defined functions. These functions have their own scope, which means that variables used within a function are not available outside of it, and variables defined outside of a function are not available within it. For this reason, a variable inside of a function can have the same name as one outside of it and still be an entirely different variable with different values (e.g., $total in Script 3.9).

To alter the variable scope within a function, you can use the global statement.

function function_name() {
   global $var;
$var = 'value';

In this example, $var inside of the function is now the same as $var outside of it. This means that the function $var already has a value of value, and if that value changes inside of the function, the external $var's value will also change.

Another option for circumventing variable scope is to make use of the superglobals: $_GET, $_POST, $_SESSION, etc. These variables are automatically accessible within your functions (hence, they are superglobal).

To use global variables:

  1. Open handle_calculator.php (refer to Script 3.9) in your text editor.
  2. Change the function definition to (Script 3.10)
    function calculate_total () {
       global $total;
       $total = ($_POST['quantity'] * $_POST['price']) * ($_POST['taxrate'] + 1);
       $total = number_format ($total, 2);
    Since I've been using the superglobals anyway, I can rewrite the function so that it automatically uses these variables instead of passing variables to it. Similarly, instead of returning the $total value, I can give it global scope.
  3. Change the function call line to
    $total = 0;
    calculate_total ();
    Despite the use of $_POST variables, I still need to call the function for the calculations to be made. I also initialize the $total variable as 0 for safety measures.
  4. Save the file, upload to your server, and test in your Web browser ( Figure 3.13 ).

    Figure 3.13 The result of the calculations.

Example 3.10. Since $_POST is a superglobal variable, its values can be accessed within functions.

1   <?php # Script 3.10 - handle_calculator.php
3   // Set the page title and include the HTML header.
4   $page_title = 'Calculator';
5   include ('./');
7   # ----------------------
8   // This function calculates a total based upon quantity, price, and tax and then returns the results.
9   function calculate_total () {
11      global $total;

   12      $total = ($_POST['quantity'] * $_POST['price']) * ($_POST['taxrate'] + 1);
13      $total = number_format ($total, 2);
15  } // End of calculate_total() function.
16  # ----------------------
18  // Main conditional.
19  if (is_numeric($_POST['quantity'])) { // Is the quantity a number?
21      $total = 0;

   22      calculate_total ();
23      echo "<p>You are purchasing <b>{$_POST['quantity']}</b> widget(s) at a cost of <b>\${$_POST['price']}</b> each. With tax, the total comes to <b>\$$total</b>.</p>\n";
25  } else { // Quantity is not a number.
26      echo '<p><b>Please enter a valid quantity to purchase!</b></p>';
27  }
29  include ('./'); // Include the HTML footer.
30  ?>
  • + Share This
  • 🔖 Save To Your Account