Programming Tips - PHP: How do global variables work in PHP?

Date: 2011jul15 Created: 2010mar27 Language: php Q. PHP: How do global variables work in PHP? A. Declare outside a function:
$myglobal = 'http://www.example.com';
The you can use inside a function two ways: Method one:
function useGlobalVariable1() { global $myglobal; print "The global is $myglobal\n"; }
Method two:
function useGlobalVariable2() { $value = $GLOBALS['myglobal']; print "The global is $value\n"; }
The first method is cleaner to me. Just make sure you give your globals big names or possibly start with the letter "g". One advantage to the second method is that your global can begin undefined:
function useGlobalVariableU() { if (!isset($GLOBALS['myglobal'])) { $GLOBALS['myglobal'] = slowFunction(); } $value = $GLOBALS['myglobal']; print "The global is $value\n"; }
In this case you don't declare it outside the function.