Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top