unset()静态变量不起作用?

duk*_*vin 2 php unset

请参阅此代码: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
Run Code Online (Sandbox Code Playgroud)

输出:

array before deleting:
Array
(
    [0] => 79
    [1] => 49
    [2] => 133
)
array before deleting:
Array
(
    [0] => 79
    [1] => 49
    [2] => 133
)
Run Code Online (Sandbox Code Playgroud)

为什么数组$x在未设置时不会被删除?

eve*_*Guy 8

如果未设置静态变量,则仅在未设置的函数中销毁该变量.以下对函数的调用(getValues())将在取消设置之前使用该值.

这也提到了unset函数的文档. http://php.net/manual/en/function.unset.php

  • 有没有办法销毁静态变量? (2认同)
  • 如果 $delete 为 true,那么我认为你可以在使用 unset($x); 之前使 $x = null 这样,下次调用该函数时,它将使用 null 作为 $x 的值,因为它是取消设置之前 $x 的最后一个值。 (2认同)