unset() static variable doesn't work?

前端 未结 2 763
庸人自扰
庸人自扰 2021-01-21 12:02

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

function getvalues($delete = false)
{
   static $x;
   if($delete)
   {
      echo \"array before deleting:\\n\";
             


        
相关标签:
2条回答
  • 2021-01-21 12:33

    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
    
    0 讨论(0)
  • 2021-01-21 12:58

    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

    0 讨论(0)
提交回复
热议问题