Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP global or $GLOBALS

Is there a best practice / recommendation when I want to use a variable declared outside of a function when it comes to using:

  1. global $myVar
  2. $GLOBALS['myVar']

Thank you.

like image 989
Francisc Avatar asked Aug 26 '10 09:08

Francisc


People also ask

Should I use global in PHP?

Like anything else, use "global" variables, procedural code, a particular framework and OOP because it makes sense, solves a problem, reduces the amount of code you need to write or makes it more maintainable and easier to understand, not because you think you should.

Are PHP variables global?

$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.

What is difference between global and GLOBALS in PHP?

They are two different things. global is a keyword which tells that the variable is from a global scope. E.g. if you're about to access a variable inside a function that's defined outside you'll need to use the global keyword to make it accessible in the function. $GLOBALS is a superglobal array.

What is auto global in PHP?

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods. Note: Variable availability.


1 Answers

Well, you should only use globals in limited circumstances, but to answer your question:

  1. global is potentially marginally faster (it will rarely make a difference).
  2. $GLOBALS (not $GLOBAL) is more readable, because every time you see it, you know you are accessing/changing a global variable. This can be crucial in avoiding nasty bugs.
  3. Inside the function, if you want to unset a global variable, you must use unset($GLOBALS['varname']), not global $varname; unset($varname);.

As to points 1 and 2, I'll quote Sara Golemon here:

What does that mean for your use of the $GLOBALS array? That's right, the global keyword is technically faster. Now, I want to be really clear about one thing here. The minor speed affordance given by using your globals as localized [compiled variables] needs to be seriously weighed against the maintainability of looking at your code in five years and knowing that $foo came from the global scope. something_using($GLOBALS['foo']); will ALWAYS be clearer to you down the line than global $foo; /* buncha code */ something_using($foo); Don't be penny-wise and pound foolish..

like image 106
Artefacto Avatar answered Sep 24 '22 00:09

Artefacto