Is there a best practice / recommendation when I want to use a variable declared outside of a function when it comes to using:
global $myVar
$GLOBALS['myVar']
Thank you.
Is there a best practice / recommendation when I want to use a variable declared outside of a function when it comes to using:
global $myVar
$GLOBALS['myVar']
Thank you.
Well, you should only use globals in limited circumstances, but to answer your question:
global
is potentially marginally faster (it will rarely make a difference).$GLOBALS
(not$GLOBAL
) is more readable, because every time you see it, you know you are accessing/changing a global variable. This can crucial in avoiding nasty bugs.unset($GLOBALS['varname'])
, notglobal $varname; unset($varname);
.As to points 1 and 2, I'll quote Sara Golemon here:
What you should really do is pass the variable to the function instead of using a global at all.
An example how to change a variable outside of the function via passing it as reference parameter:
global $var;
is equivalent to$var =& $GLOBALS['var']
.Some people suggested that it is faster than using
$GLOBALS
, however it's not necessarily the case. If you use the variable only once,$GLOBALS
will be faster, because you won't waste time for assignment.However, if you do use the variable multiple times, using
global
(or the equivalent assignment) is faster, because search the array for thevar
key only once.That's it about speed. However, the speed difference is really small, and readability is more important. However, different people have different preferences about readability -- I prefer
global
, some other people answering here prefer$GLOBALS
, so it's up to you to decide what looks better.I would go for global in the top of your function. In that way, you can easily see what globals are used.
I wold say, it's recommended not to use Globals in OOP, there should always be a better way