1

global $user vs $user = $GLOBALS['user']

by using "global $var" to get a global variable, do we get a copy of the global var or get a reference to that global variable?

global $user;

Is $user a copy of global object or is a reference to actual global variable?

Thanks.

gilzero
  • 1,832
  • 4
  • 19
  • 26

4 Answers4

2

by using it with global $var; you always have a local variable that references the global variable.

Following code:

$var = 1;

function test() {
  global $var;

  $var++;
}

test();
echo $var;

is equivalent to:

$var = 1;

function test() {
  $GLOBALS['var']++;
}

test();
echo $var;
hakre
  • 193,403
  • 52
  • 435
  • 836
ioseb
  • 16,625
  • 3
  • 33
  • 29
2

By using global $var the global variable named "var" will be imported into the local scope of the function (that is done by creating a reference).

That is different to $GLOBALS which is a superglobal variable. That is always everywhere regardless of the scope.

However that's different to references. If you really want to understand about the variables and how this is with references to variables, I suggest the PDF by Derick Rethans: References in PHP: An In-Depth Look (PDF).

hakre
  • 193,403
  • 52
  • 435
  • 836
  • Global/Local Related: [Make all variables global, PHP](http://stackoverflow.com/q/1909647/367456) – hakre Jun 11 '12 at 14:45
0

Quoting $GLOBALS' documentation:

An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

A simple test case:

$foo = "foo";
echo $GLOBALS["foo"];         // foo
echo $GLOBALS["foo"] = "bar"; // bar
echo $foo;                    // bar
Alexander
  • 23,432
  • 11
  • 63
  • 73
0

Neither. The compiler resolves usage of that variable name to the corresponding variable in global scope.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358