PHP unset() 函数

PHP 可用的函数PHP 可用的函数

unset() 函数用于销毁给定的变量。

PHP 版本要求: PHP 4, PHP 5, PHP 7

语法

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

参数说明:

  • $var: 要销毁的变量。

返回值

没有返回值。

实例

实例

<?php
// 销毁单个变量
unset ($foo);
 
// 销毁单个数组元素
unset ($bar['quux']);
 
// 销毁一个以上的变量
unset($foo1, $foo2, $foo3);
?>

如果在函数中 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

PHP 可用的函数PHP 可用的函数

0 个评论

要回复文章请先登录注册