note 24904 added to language.variables.scope
| From: | madeinlisboa at yahoo dot com | Date: | Wed, 04 Sep 2002 14:14:23 +0000 |
| Subject: | note 24904 added to language.variables.scope | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-36109@lists.php.net to get a copy of this message | ||
Be careful when using static vars inside classes. They don't have the behavior you expect when
dealing with more than one instance of the class. Their values remain across instances, which I
think is wrong, but, hey, whos me?
Example:
Class xpto
{
function some()
{
static $x = 0;
echo $x;
++$x;
}
}
$i1 = new xpto;
$i1->some();
$i2 = new xpto;
$i2->some();
First call to some(), using $il, will display 0 and add 1 to $x
Second call to some(), using $il2, will display 1, not 0 (value of $x remains across instances)
Static vars are not independent. They are shared by every instance of an object!!!
If you need to overcome this, create an intermediary method, which will send a reset parameter to
some(), so that the method knows it is a new instance:
Class xpto
{
function some($reset)
{
static $x = 0;
if($reset) $x=0;
echo $x;
++$x;
}
function some_before()
{
$this->some(true);
}
}
$i1 = new xpto;
$i1->some_before();
$i2 = new xpto;
$i2->some_before();
--
http://www.php.net/manual/en/language.variables.scope.php
http://master.php.net/manage/user-notes.php?action=edit+24904
http://master.php.net/manage/user-notes.php?action=delete+24904
http://master.php.net/manage/user-notes.php?action=reject+24904