note 44412 added to function.unset
| From: | thorry at thorry dot net | Date: | Thu, 05 Aug 2004 06:15:17 +0000 |
| Subject: | note 44412 added to function.unset | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-73970@lists.php.net to get a copy of this message | ||
The documentation is not entirely clear when it comes to static variables. It says:
If a static variable is unset() inside of a function, unset() destroys the variable and all its
references.
<?php
function foo()
{
static $a;
$a++;
echo "$a\n";
unset($a);
}
foo();
foo();
foo();
?>
The above example would output:
1
2
3
And it does! But the variable is NOT deleted, that's why the value keeps on increasing,
otherwise the output would be:
1
1
1
The references are destroyed within the function, this handeling is the same as with global
variables, the difference is a static variable is a local variable.
Be carefull using unset and static values as the output may not be what you expect it to be. It
appears to be impossible to destroy a static variable. You can only destroy the references within
the current executing function, a successive static statement will restore the references.
The documentation would be better if it would say:
"If a static variable is unset() inside of a function, unset() destroys all references to the
variable. "
Example: (tested PHP 4.3.7)
<?php
function foo()
{
static $a;
$a++;
echo "$a\n";
unset($a);
echo "$a\n";
static $a;
echo "$a\n";
}
foo();
foo();
foo();
?>
Would output:
1
1
2
2
3
3
----
Manual Page -- http://www.php.net/manual/en/function.unset.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+44412
Delete -- http://master.php.net/manage/user-notes.php?action=delete+44412&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+44412&report=yes
Search -- http://master.php.net/manage/user-notes.php