note 25304 added to language.variables.scope
| From: | gSwPw at cMs dot SuUoCrKeSgon dot edu | Date: | Wed, 18 Sep 2002 19:35:46 +0000 |
| Subject: | note 25304 added to language.variables.scope | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-36906@lists.php.net to get a copy of this message | ||
Thus spake madeinlisboa@yahoo.com:
> Static vars are not independent. They are shared by every instance of
> an object!!!
>
Rather, class instances share methods. For some purposes, method names can be viewed as static
variables referring to functions. The 'xpto->some()' method contains the static
variable '$x', and so every call to xpto->some() from an xpto object accesses the same
variable that '$x' refers to.
> 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:
>
Doesn't this almost defeat the purpose of a static variable? The call to
xpto->some_before() resets the static variable '$x' for EVERY xpto object.
Furthermore, calls to xpto->some() still increment $x for every xpto object.
e.g.:
$i1 = new xpto;
$i1->some_before();
/* $x in $i1->some() is now 1*/
$i2 = new xpto;
$i2->some_before();
$i2->some();
/* $x in $i1->some() is now 2*/
The appropriate way to preserve variables across methods calls is to use an instance variable.
e.g.:
Class xpto
{
var $x;
function xpto() {
$this->x = 0;
}
function some()
{
echo $this->x;
++$this->x;
}
}
Note you cannot (I believe) reassign a method, as you can in javascript and Perl; this is why method
names cannot always be viewed as static function references. PHP provides variable functions,
rather than function references, to dynamically change function calls.
--
http://www.php.net/manual/en/language.variables.scope.php
http://master.php.net/manage/user-notes.php?action=edit+25304
http://master.php.net/manage/user-notes.php?action=delete+25304
http://master.php.net/manage/user-notes.php?action=reject+25304