mercredi 30 septembre 2015

Static variable in method doesn't reset on instance unset

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):

Example 1 - using a static variable inside class method

<?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.

Aucun commentaire:

Enregistrer un commentaire