unset函数是php自带的一个销毁变量的函数,我们介绍了利用unset来销毁静态变量与全局变量的方法,同时出可以销毁数组变量哦,下面我们看实例.
例 1. unset() 示例
实例代码如下:
<?php // 销毁单个变量 unset ($foo); // 销毁单个数组元素 unset ($bar['quux']); // 销毁一个以上的变量 unset ($foo1, $foo2, $foo3); ?>
unset() 在函数中的行为会依赖于想要销毁的变量的类型而有所不同.
如果在函数中 unset() 一个全局变量,则只是局部变量被销毁,而在调用环境中的变量将保持调用 unset() 之前一样的值.
实例代码如下:
<?php function destroy_foo() { global $foo; unset($foo); } $foo = 'bar'; destroy_foo(); echo $foo; ?>
上边的例子将输出:
bar
如果在函数中 unset() 一个通过引用传递的变量,则只是局部变量被销毁,而在调用环境中的变量将保持调用 unset() 之前一样的值.
实例代码如下:
<?php function foo(&$bar) { unset($bar); $bar = "blah"; } $bar = 'something'; echo "$bar\n"; foo($bar); echo "$bar\n"; ?>
上边的例子将输出:
something something
unset() 静态变量,严格讲,使用 unset() 销毁静态变量,只是断开了变量名和变量值之间的引用.
例子,实例代码如下:
<?php function foo() { static $b; $a++; $b++; echo "$a---$bn"; unset($a,$b); var_dump($a); var_dump($b); echo "######################n"; } foo(); foo(); foo(); ?>
运行该例子,输出:
1---1 NULL NULL ####################### 1---2 NULL NULL ####################### 1---3 NULL NULL #######################
unset() 全局变量,同 unset() 静态变量一样,如果在函数中 unset() 一个全局变量,则只是局部变量被销毁,而在调用环境中的变量将保持调用 unset() 之前一样的值.
试着比较如下两个例子:
实例代码如下:
<?php function destroy_foo() { global $foo; unset($foo); } $foo = 'bar'; destroy_foo(); echo $foo; ?> <?php function destroy_foo() { global $foo; unset($GLOBALS['foo']); } $foo = 'bar'; destroy_foo(); echo $foo; ?>
运行第一个例子会输出:bar ,而第二个例子则不会有任何输出.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver CS6
Visual web development tools