閱讀518 返回首頁    go 魔獸


php之unset()詳解

unset

(PHP 4, PHP 5)

unset — 釋放給定的變量

說明

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

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

參數

var

要銷毀的變量。

...

其他變量……

返回值

沒有返回值。

更新日誌

版本 說明
4.0.1 添加了多個參數的支持。

範例

Example #1 unset() 示例

<?php
// 銷毀單個變量
unset ($foo);

// 銷毀單個數組元素
unset ($bar['quux']);

// 銷毀一個以上的變量
unset($foo1$foo2$foo3);
?>

Example #2 使用 (unset) 類型強製轉換

(unset) 類型強製轉換常常和函數 unset() 引起困惑。 為了完整性,(unset) 是作為一個 NULL 類型的強製轉換。它不會改變變量的類型。

<?php
$name 
'Felipe';

var_dump((unset) $name);
var_dump($name);
?>

以上例程會輸出:

NULL
string(6) "Felipe"

注釋

Note因為是一個語言構造器而不是一個函數,不能被 可變函數 調用。

Note:

It is possible to unset even object properties visible in current context.

Note:

在 PHP 5 之前無法在對象裏銷毀 $this

Note:

在 unset() 一個無法訪問的對象屬性時,如果定義了 __unset() 則對調用這個重載方法。

參見

最後更新:2017-04-03 05:38:56

  上一篇:go php之內存管理基礎
  下一篇:go php之str_replace詳解