[初探PHP] unset() 函數

unset
php

-- 釋放給定的變量函數

描述: spa

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

unset() 銷燬指定的變量code

例子1.unset()示例作用域

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

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

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

        若是在函數中 unset() 一個全局變量,則只是局部變量被銷燬,而在調用環境中的變量將保持調用 unset() 以前同樣的值。io

<?php
    function foor(){
        qlbal $foo;
        unset($foo); // 這裏unset()的做用域只在這個foor()函數中
    }
    
    $foo = 'bar';
    foor();
    echo $foo; // bar
?>

        若是在函數中 unset() 一個經過引用傳遞的變量,則只是局部變量被銷燬,而在調用環境中的變量將保持調用 unset() 以前同樣的值。function

<?php
    function foo(&$bar){
        unset($bar);
        $bar = "blah";
    }
    
    $bar = 'someThing';
    echo "$bar\n"; // someThing
    
    foo($bar);
    echo "$bar\n"; // someThing
?>

        若是在函數中 unset() 一個靜態變量,則 unset() 將銷燬此變量及其全部的引用。class

<?php
    function foo(){
        static $a;
        $a++;
        echo "$a\n";
        unset($a);
    }
    
    foo(); // 1
    foo(); // 2
    foo(); // 3
?>

        若是你想在函數中 unset() 一個全局變量,可以使用 $GLOBALS 數據來實現。變量

<?php
    function foo(){
        unset($GLOBALS['bar']);
    }
    
    $bar = "someThing";
    foo();
?>
相關文章
相關標籤/搜索