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 可用的函數