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 に答える