Why does the definition of the $ GLOBALS variable ['foo'] not work?


The following code produces a warning:

$GLOBALS['foo'] = "Example content<BR><BR>";
echo $foo; // that works!

function Test()
    echo $foo; // that doesn't work!

The warning is:

Notice: Undefined variable: foo

How come ?

Inside the function, $foo is out of scope unless you call it as $GLOBALS['foo'] or use global $foo. Defining a global with $GLOBALS, although it improves readability, does not automatically reserve the variable name for use in all scopes. You still need to explicitly call the global variable inside lower scopes to make use of it.

function Test()
    echo $GLOBALS['foo'];

    // Or less clear, use the global keyword
    global $foo;
    echo $foo;

It's even possible to have both a local and a global $foo in the same function (though not at all recommended):

$GLOBALS['foo'] = "foo! :)";
function getFoo()
  $foo = "boo :(";
  echo $GLOBALS['foo'] . "\n"; // Global $foo
  echo $foo;            // Local scope $foo since it has no global keyword

// foo! :)
// boo :(

Review the PHP documentation on variable scope and the $GLOBALS documentation for more examples.