【问题标题】:unset() static variable doesn't work?unset() 静态变量不起作用?
【发布时间】:2012-03-15 16:05:48
【问题描述】:

查看这段代码: 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在取消设置时没有被删除?

【问题讨论】:

  • 做 $x = null;在函数之外取消设置它。在我的例子中,语法是 class_name::$static_property = null;

标签: php unset


【解决方案1】:

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

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

【讨论】:

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

来自Doc

如果静态变量在函数内部是 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

【讨论】:

  • 我不知道这个...那我怎样才能销毁变量呢?
猜你喜欢
  • 2014-08-12
  • 2013-10-06
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2018-12-28
  • 2018-07-29
  • 1970-01-01
相关资源
最近更新 更多