unset() static variable doesn't work?

筅森魡賤 提交于 2019-12-02 04:30:13

问题


See this code: http://codepad.org/s8XnQJPN

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

Output:

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

Why is the array, $x not being deleted when it is being unset?


回答1:


If a static variable is unset, it destroys the variable only in the function in which it is unset. The following calls to the function (getValues()) will make use of the value before it was unset.

This is mentioned the documentation of the unset function as well. http://php.net/manual/en/function.unset.php




回答2:


From the Doc

If a static variable is unset() inside of a function, unset() destroys the variable only in the context of the rest of a function. Following calls will restore the previous value of a variable.

function foo()
{
    static $bar;
    $bar++;
    echo "Before unset: $bar, ";
    unset($bar);
    $bar = 23;
    echo "after unset: $bar\n";
}

foo();
foo();
foo();

The above example will output:

Before unset: 1, after unset: 23
Before unset: 2, after unset: 23
Before unset: 3, after unset: 23


来源:https://stackoverflow.com/questions/9443753/unset-static-variable-doesnt-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!