note 24904 deleted from language.variables.scope by aidan
| From: | aidan@php.net | Date: | Sun, 04 Jul 2004 02:51:32 +0000 |
| Subject: | note 24904 deleted from language.variables.scope by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-72507@lists.php.net to get a copy of this message | ||
Note Submitter: madeinlisboa@yahoo.com
----
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();