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, and 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>\$d = $d</p>\n");
}
echo("<p>\$d = $d</p>\n"); // Outside function, $d is local, and so is not defined (NULL) and displays an error if display_errors are turned on

$d = 10

$d =

Back