Tanatos Daniel
Tanatos Daniel

Reputation: 578

Global references in php

I read this article on php.net:

"When you declare a variable as global $var you are in fact creating reference to a global variable. That means, this is the same as:

<?php
$var =& $GLOBALS["var"];
?>

This also means that unsetting $var won't unset the global variable."

What I understand from this is that when you declare a variable as global $var, you set another name for the variable name $GLOBALS["var"]. So if you echo one or another, you get the same thing. But I find the last sentence confusing, since the following snippet outputs 'red':

$GLOBALS['var']='blue';
global $var;  //This is supposed to be equivalent to $var=& $GLOBALS["var"];
//echo $var,'<br/>';
$var='red';
echo $GLOBALS['var']; //I would expect this to output 'blue', instead of 'red'

I was expecting the output to be 'blue' since it states that unsetting $var won't unset the global variable. Where're the mistake?

If I do unset($var), how should I check that the global variable was not unset?

Upvotes: 0

Views: 143

Answers (2)

sectus
sectus

Reputation: 15464

$var='red';

It's not unsetting, it's assigment. Assigment affects to global variable.

This also means that unsetting $var won't unset the global variable.

It's about using unset function. unset($var) removes variable from current scope, but global variable is still there.

Upvotes: 2

Machavity
Machavity

Reputation: 31614

You need to understand that you missed that minor detail, the &. What that does, is it says you want the original reference and not a copy of the variable.

function test() {
    $var = $GLOBALS['x'];
    $var2 = &$GLOBALS['x'];
    echo $GLOBALS['x'] . "\n";
    $var2 = 'red';
    echo $var . "\n" . $GLOBALS['x'];

}

$x = 'blue';
test();

This outputs

blue
red

You'll note that $var was assigned to global version, but what happened was PHP only copied $x. With $var2, we told PHP that we wanted the reference, or, in other words, the actual address of $x. This makes a huge difference because $var is only a copy. Changing it only changes the copy. Note in my example that I changed the value of $x, but only $var2 reflected that change. $var still had what $x was at the beginning.

Upvotes: 1

Related Questions