Variable Scope

Variable Scope

Unless otherwise declared, a variable's scope is limited to the function (named block of code) or block of code where it is defined. A variable cannot be used outside its scope.

<?php
   // Define a function
   function birthday() {
      $age = 1;  // Set local variable age to 1
      echo $age;
   }

   //  Use the function
   $age = 30;           // Set age to 30 -- not the same $age as in the function
   birthday();          // Call the function
   echo "<BR /">$age;   // This will print 30
?>
 

A global variable has a scope that extends beyond these boundaries--its value will be the same wherever you define it as global:

<?php
   // Define a function
   function birthday() {
      global $age;  // Declare that $age is global
      $age = $age + 1;  // Add 1 to age
      echo $age;        // This will print 31
   }

   $age = 30;   // Set age to 30
   birthday();  // Call the function
   echo $age;   // This will print 31
?> 

A static variable is one whose value is preserved between different function calls.

<?php
   // Define a function
   function birthday() {
      static $age = 0;  // Set static variable age to 1
      $age = $age + 1;  // Add 1 to age
      echo "Birthday number $age<br ?>";   // Print its value
   }

   $age = 30;   // Set age to 30
   birthday();  // Call the function-- prints 1
   birthday();  // Call the function again -- prints 2
   echo "Age: $age<br ?>";   // This will print 30
?> 

Super Globals

PHP also has certain super globals such as $_SERVER and $_GET, that provide information about the script's environment.

Click here for the in class example.