unset() 销毁指定的变量。
unset() 在函数中的行为会依赖于想要销毁的变量的类型而有所不同。
如果在函数中 unset() 一个全局变量,则只是局部变量被销毁,而在调用环境中的变量将保持调用 unset() 之前一样的值。
<?php
function destroy_foo() {
global $foo;
unset($foo);
}
$foo = 'bar';
destroy_foo();
echo $foo;
?>
以上例程会输出:
bar
如果您想在函数中 unset() 一个全局变量,可使用 $GLOBALS 数组来实现:
<?php
function foo()
{
unset($GLOBALS['bar']);
}
$bar = "something";
foo();
?>
如果在函数中 unset() 一个通过引用传递的变量,则只是局部变量被销毁,而在调用环境中的变量将保持调用 unset()之前一样的值。
<?php
function foo(&$bar) {
unset($bar);
$bar = "blah";
}
$bar = 'something';
echo "$bar\n";
foo($bar);
echo "$bar\n";
?>
以上例程会输出:
something something
如果在函数中 unset() 一个静态变量,那么在函数内部此静态变量将被销毁。但是,当再次调用此函数时,此静态变量将被复原为上次被销毁之前的值。
<?php
function foo()
{
static $bar;
$bar++;
echo "Before unset: $bar, ";
unset($bar);
$bar = 23;
echo "after unset: $bar\n";
}
foo();
foo();
foo();
?>
以上例程会输出:
Before unset: 1, after unset: 23 Before unset: 2, after unset: 23 Before unset: 3, after unset: 23