0

The PHP manual says 'unset() destroys the specified variables.' It has the following example:

<?php
function destroy_foo() 
{
    global $foo;
    unset($foo);
}

$foo = 'bar';
destroy_foo();
echo $foo;
?>

The above code will output:

bar

So what has 'unset' done? Don't get it. Please explain.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
  • 3
    global makes a local variable a reference to a variable in the global scope. When you unset inside the function, you're unsetting that reference, not the variable "above". `unset($GLOBALS['foo'])` would kill the value. – Marc B May 23 '13 at 17:17
  • That should be added as an answer and accepted – Kai Qing May 23 '13 at 17:21
  • @MarcB Please add your response as a Q, so I can accept. Thanks. –  May 23 '13 at 17:30

2 Answers2

3

global makes a local variable a reference to a variable in the global scope. When you unset inside the function, you're unsetting that reference, not the variable "above".

e.g.

function foo() {
   global $bar;
   unset($bar);
}

is for the most part doing the same thing as

function foo() {
   $bar = &$GLOBALS['bar'];
   unset($bar); // kill the local reference, not the global variable.
}

it's just a bit easier on the eyes.

Marc B
  • 356,200
  • 43
  • 426
  • 500
0

Apart from Marc's comment, unset is often used in a variety of ways. Just one example -

Unset a certain item in an array:

$arr = array("a","b","c");
unset($arr['b']);
print_r($arr);

//gives us
//array("a","c");
Kai Qing
  • 18,793
  • 5
  • 39
  • 57