Reputation: 5760
Interesting behavior in PHP 5.6.12-arm and PHP 7 RC3 (though I guess it's like that in all version, I just wanted to note which versions I've used to test):
<?php
class Foo {
public function Bar() {
static $var = 0;
return ++$var;
}
}
$Foo_instance = new Foo;
print $Foo_instance->Bar(); // prints 1
print PHP_EOL;
unset($Foo_instance);
$Foo_instance2 = new Foo;
print $Foo_instance2->Bar(); // prints 2 - but why?
print PHP_EOL;
?>
Question: How can a 2 be printed, since we unseted the whole instance before calling Foo->Bar() again?
Please note that this question and its answers don't answer my question.
Best regards.
Upvotes: 1
Views: 182
Reputation: 36944
You can look in the php documentation of variables scope.
if you declare a variable as static inside a function, it's static for the whole class and all of its instances, not for each object.
So, a static variable is not related to a single instance.
Upvotes: 1