3

请参阅此代码: 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

输出:

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

为什么数组$x在取消设置时没有被删除?

4

2 回答 2

9

如果一个静态变量未设置,它只会在未设置它的函数中销毁该变量。以下对函数 (getValues()) 的调用将使用未设置之前的值。

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

于 2012-02-25T12:05:30.837 回答
3

文档

如果静态变量在函数内部是 unset(),则 unset() 仅在函数其余部分的上下文中销毁该变量。以下调用将恢复变量的先前值。

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
于 2012-02-25T12:04:48.787 回答