PHP Unset


PHP unset() is used to destroy one or more variables, no return value .

grammar:

void unset(mixed var[, mixed var[, ...]])

example:

// Destroy a single variable
unset($var);

// Destroy a single array element
unset($arr['a']);

// Destroy more than one variable
unset($var1, $var2, $var3)

unset() static variable

Strictly speaking, the use of unset() Destroy static variables, but the variable name and the variable value of the reference.

example:

≪? Php
function foo() {
    Static $b;
    $a ++;
    $b ++;
    echo " $a --- $bn " ;;
    unset($a, $b);
    var_dump($a);
    var_dump($b);
    echo " ###################### n " ;;
}

foo();
foo();
foo();
?>

Run the example and output:

1 --- 1
NULL
NULL
#######################
1 --- 2
NULL
NULL
#######################
1 --- 3
NULL
NULL
#######################

unset() global variable

As with the unset() static variable, if a global variable is unset() in a function, only the local variable is destroyed and the variable in the calling environment remains the same value before calling unset().

Try to compare the following two examples:

function destroy_foo() {
    Global $foo;
    unset($foo);
}

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

function destroy_foo() {
    global $foo;
    unset($GLOBALS['foo']);
}

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

Running the first example will output: bar, while the second example will have no output.

Tip
  • In many cases, you can let PHP automatically manage the variables without regard to the unset() variable. Only in the specific, the need for a variable must be used when the air. Such as: the user log out, in order to ensure the security of information, you can use unset() empty session content.
  • unset() Try not to use static variables, because it is the definition of static variables contrary to the original intention.
  • unset() is a language construct, not a function, so it can not be called by a variable function.



Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook