2012-02-25 15 views
3

看到這個代碼: http://codepad.org/s8XnQJPNunset()靜態變量不起作用?

function getvalues($delete = false) 
{ 
    static $x; 
    if($delete) 
    { 
     echo "array before deleting:\n"; 
     print_r($x); 
     unset($x); 
    } 
    else 
    { 
     for($a=0;$a<3;$a++) 
     { 
     $x[]=mt_rand(0,133); 
     } 
    } 
} 

getvalues(); 
getvalues(true); //delete array values 
getvalues(true); //this should not output array since it is deleted 

輸出:

array before deleting: 
Array 
(
    [0] => 79 
    [1] => 49 
    [2] => 133 
) 
array before deleting: 
Array 
(
    [0] => 79 
    [1] => 49 
    [2] => 133 
) 

爲什麼陣列,$x沒有當它正在被刪除,未設置?

+0

do $ x = null;除了它的功能之外。在我的情況下,語法是class_name :: $ static_property = null; – 2017-08-02 19:09:03

回答

7

如果一個靜態變量是未設置,它破壞只在它未設置該函數的變量。以下對函數(getValues())的調用將在未設置之前使用該值。

這裏還提到了未設置函數的文檔。 http://php.net/manual/en/function.unset.php

+1

有沒有辦法銷燬靜態變量? – dukevin 2012-02-25 12:09:04

+1

其中$ delete是真的,那麼我認爲你可以讓$ x = null在使用unset($ x)之前;這樣你下次調用該函數時,它將使用null作爲$ x的值,因爲它是$ x的最後一個值,在它未被設置之前。 – everconfusedGuy 2012-02-25 12:13:21

+0

工作,謝謝 – dukevin 2012-02-25 12:15:36

3

Doc

如果一個靜態變量被複位()的函數的內部,未設置(),刪除僅在函數的其餘部分的上下文 變量。調用 之後將恢復變量的前一個值。

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 
+1

我不知道這個......那我該如何摧毀這個變量呢? – dukevin 2012-02-25 12:05:49