[development] Beware of static and unset together

Darrel O'Pry dopry at thing.net
Thu May 3 23:41:52 UTC 2007


On Fri, 2007-04-06 at 00:45 -0700, Karoly Negyesi wrote:
> Hi,
> 
> So says the PHP manual about unset
> 
> "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."
> 
> This will lead to really weirdo stuff if you have:
> 
> function foo($refresh = FALSE) {
>    static $storage;
>    if ($refresh) {
>      echo "refreshing\n";
>      unset($storage);
>    }
> 
>    if (!isset($storage)) {
>      $storage = microtime();
>    }
>    return $storage;
> }
> echo foo() ."\n";
> echo foo(TRUE) ."\n";
> echo foo() ."\n";
> 
> Observe how the third and the first results are the same as if the refresh  
> did not happen.

Sounds like a good excuse for properly initializing your static's and
reinitializing them when the need to be reset. 



More information about the development mailing list