note 25304 deleted from language.variables.scope by aidan
| From: | aidan@php.net | Date: | Sun, 04 Jul 2004 02:51:23 +0000 |
| Subject: | note 25304 deleted from language.variables.scope by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-72506@lists.php.net to get a copy of this message | ||
Note Submitter: gSwPw@cMs .SuUoCrKeSgon.edu
----
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.