PHP unset() 函数

PHP 教程 · 2019-01-31 22:13:31

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 教程 文章: https://www.codercto.com/courses/l/5.html

查看所有标签

Head First PHP & MySQL

Head First PHP & MySQL

Lynn Beighley、Michael Morrison / O'Reilly Media / 2008-12-29 / USD 44.99

If you're ready to create web pages more complex than those you can build with HTML and CSS, Head First PHP & MySQL is the ultimate learning guide to building dynamic, database-driven websites using P......一起来看看 《Head First PHP & MySQL》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具