I came across some unexpected behavior with static variables defined inside methods of objects that are shared between instances. This is probably a known behavior, but when I look at the PHP documentation, I cannot find instances of statically defined variables in object methods.
The following is a description of the behavior I encountered:
<?php class Foo { public function dofoo() { static $i = 0; echo $i++ . '<br>'; } } $f = new Foo; $g = new Foo; $f->dofoo(); // expected 0, got 0 $f->dofoo(); // expected 1, got 1 $f->dofoo(); // expected 2, got 2 $g->dofoo(); // expected 0, got 3 $g->dofoo(); // expected 1, got 4 $g->dofoo(); // expected 2, got 5
Now I expected it to $ibe static on one instance, but actually $ishared between instances. For my own guidance, can someone explain why this is so, and where is it documented at php.net?
$i
.
, ,
<?php class Foo { protected $_count = 0; public function doFoo() { echo $this->_count++, '<br>'; } }
: , . . , :
. .
, script ( ), "" ( , ). , , "", , .
, PHP , "scope" .
, ( hobodave), "" " ", , ( ) , "scoped" ( $foo, $foo).
, PHP 5 ( "static" " " ), , PHP.
, , PHP - , . , , PHP-, " ", , , , .
, , .
, .
class Foo { private $i = 0; public function dofoo() { echo $this->i++ . '<br>'; } }
. PHP 4 (, , ). / PHP 5.
- . , .
. , .
7 , .
, ?!? , , .
:
namespace Statics; class Foo { protected static $_count; public function Bar() { return self::$_count++; } public function __construct() { self::$_count = 0; } }
require 'Foo.php'; use Statics\Foo; $bar = new Foo(); echo $bar->bar().'<br>'; echo $bar->bar().'<br>'; echo $bar->bar().'<br>'; $barcode = new Foo(); echo $barcode->bar().'<br>'; echo $barcode->bar().'<br>'; echo $barcode->bar().'<br>'; 0 1 2 0 1 2
0! , , .
, , , !
namespace Statics; class Foo { //default value protected static $_count = 0; public function Bar() { return self::$_count++; } public function __construct() { //do something else } }
require 'Foo.php'; use Statics\Foo; $bar = new Foo(); echo $bar->bar().'<br>'; echo $bar->bar().'<br>'; echo $bar->bar().'<br>'; $barcode = new Foo(); echo $barcode->bar().'<br>'; echo $barcode->bar().'<br>'; echo $barcode->bar().'<br>'; 0 1 2 3 4 5
, , , , .
Hope this helps, and not that the answers above are incorrect, but I felt it was important to understand the whole concept from this point of view.
Regards, from Portugal!