Re: Static variable in a class method

From: Date: Thu, 14 Feb 2008 11:33:10 +0000
Subject: Re: Static variable in a class method
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-269289@lists.php.net to get a copy of this message
Pauau schreef:
I have a class method which declares a static variable within.However, across all the instances of the class, the current value on that variable
replicates. Is it the intended functionality? Example: class A {    public function foo() {        static $i=0;        $i++;    }}$obj1 = new A();$obj1->foo(); //$i = 1 $obj2 = new A();$obj2->foo(); //$i = 2 where I think it should be 1, becaue it's a new instance. 
the engine doesn't give 2 hoots about what you think it should be of course. 'static' doesn't do what you think. chances are you want to use a private instance property: <?php class Foo { private $i = 0; public function bar() { echo $this->i, "\n"; $this->i++; } } $a = new Foo; $b = new Foo; $a->bar(); $a->bar(); $a->bar(); $b->bar(); $b->bar(); ?> do please read the OO sections of the manual, some functionality, although named similarly to other languages, works quite differently - you'll avoid alot of assumption biting you in the a$$.


« previous php.general (#269289) next »