Mattia Dinosaur
Mattia Dinosaur

Reputation: 920

why the unset function is different between global and $GLOBALS?

Question

why the unset function is different between global and $GLOBALS ?

here is my code , the $GLOBALS version will echo nothing ,but the global will echo "hi".

//$GLOBALS version
<?php
function foo()
{
      unset($GLOBALS['bar']);
}
$bar ="hi";
foo();
echo $bar;
?>

the code above echo nothing

but when i change $GLOBALS['bar'] to global $bar ,it echo "hi"

//global version
<?php
function foo()
{
        global  $bar;
        unset($bar);
}

$bar = "hi";
foo();
echo $bar;
?>

I have search in google and php manual , but it seems not detail about this problem . what is the difference between GLOBALS and GLOBAL?

Upvotes: 2

Views: 81

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 78994

A true global variable imported inside a function scope with the global statement actually creates a reference to the global variable. When you use unset() it unsets the variable that is referencing the global variable, the same as other references. When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed. For example:

$a = 1;
//assign a reference to $a
$b =& $a;
unset($b);
var_dump($a);

Yields: int(1) See Unsetting References.

When you access $GLOBALS you are accessing a superglobal array and unsetting the actual variable contained in the array.

Upvotes: 1

Related Questions