At some point in your PHP programming career you will want to read a global variable inside a function - I can pretty much guarantee that, because it is a very popular thing to do. Luckily, it is made easy for you by PHP through the $GLOBALS superglobal array, which allows you to access global variables even from within functions. When it comes to the $GLOBALS array it is quite simple: all variables declared in the global scope are in the $GLOBALS array, which you can access anywhere in the script.
To demonstrate this in action, consider the following script:
What do you think that will output this time? If you guessed "wombat", you would be correct - the foo() function literally alters a variable outside of its scope, so that even after it returns control back to the main script, its effect is still felt. You can of course read variables in the same way, like this:
However, that is quite hard on the eyes. PHP allows you to use a special keyword, GLOBAL, to allow a variable to be accessed locally. For example:
Copyright 2012 Future Publishing Limited (company
registered number 2008885), a company registered
in England and Wales whose registered office is at