note 124708 deleted from language.variables.scope by crell
| From: | crell@php.net | Date: | Thu, 31 Mar 2022 19:35:12 +0000 |
| Subject: | note 124708 deleted from language.variables.scope by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-217921@lists.php.net to get a copy of this message | ||
Note Submitter: iphstich at gmail dot com
----
It seems that static variables defined within a class method or static function are stored
separately for the class and each extended class of it.
It's sort of like, every time you extend a class, functions with static variables are
re-writen, and the static variable re-created. Even if the function is defined as final!
<?php
class A {
function x () { static $x = 0; return ++$x; }
static function y () { static $y = 0; return ++$y; }
final static function z () { static $z = 0; return ++$z; }
}
class B extends A { }
class C extends B { }
// As methods, A and B have different values for x
$a = new A();
echo $a->x(); // 1
$b = new B();
echo $b->x(); // 1
echo $b->x(); // 2
// And different instances of C will have the same values for x
$c1 = new C();
$c2 = new C();
$c3 = new C();
echo $c1->x(); // 1
echo $c2->x(); // 2
echo $c3->x(); // 3
// The same behavior applies to static functions
echo A::y(); // 1
echo B::y(); // 1
echo B::y(); // 2
echo C::y(); // 1
echo C::y(); // 2
echo C::y(); // 3
// The same behavior still applies to FINAL static functions
echo A::z(); // 1
echo B::z(); // 1
echo B::z(); // 2
echo C::z(); // 1
echo C::z(); // 2
echo C::z(); // 3
?>
Tested with version 7.0.13