How variable scope works

Avariable with global scope

      $a = 10; // $a has global scope
      function show_a() {
        echo("<p>Local: $a</p>\n");  // Inside function, $a is local,
                                     // so is not defined (NULL)
                                     // and displays an error if display_errors are turned on
      }
      show_a(); // Displays nothing
      

How to access a global variable from within a function

$b = 10; // $b has global scope
function show_b() {
  global $b; // Allow global variable $a to be accessed inside function
  echo("<p>\$b = $b</p>\n");
}
show_b(); // Displays 10

$b = 10

Another way to access a global variable from within a function

$c = 10; // $c has global scope
function show_c() {
  $c = $GLOBALS['c']; // $c now refers to a local variable named $c
  echo("<p>\$c = $c</p>\n");
}
show_c(); // displays 10

$c = 10

A variable with local scope function

      function show_d() { 
        $d = 10; // $d has global scope 
        echo("<p>inside functon \$d = $d</p>\n");
      }
      echo("<p>function $d = $d</p>\n"); // Outside function, $d is local,
                                         // so is not defined (NULL) 
                                         // and displays an error if display_errors are turned on
      

inside function $d = 10

$d = // Outside function, is local, and so is not defined (NULL) and displays an error if display_errors are turned on

Restrictions on the use of global variables

$GLOBALS['c'] = 15;    // Allowed – modifies element
$GLOBALS = [];         // NOT allowed – overwrites array
unset($GLOBALS);       // NOT allowed – deletes array
array_pop($GLOBALS);   // NOT allowed – removes element	  

Back