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

Date: 2011jul15
Created: 2010mar27
Language: php

Q.  How do global variables work in PHP?


Declare outside a function:

$myglobal = '';
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 cast you don't declare it outside the function.