1.2.578. Inherited Static Variable¶
Static variables are distinct when used in an inherited static method. In PHP 8.1, the static variable will also be inherited, and shared between the two methods, like a static property.
<?php
// Code extracted from the RFC
class A {
public static function counter() {
static $i = 0;
return ++$i;
}
}
class B extends A {}
var_dump(A::counter()); // int(1)
var_dump(A::counter()); // int(2)
var_dump(B::counter()); // int(1)
var_dump(B::counter()); // int(2)
?>
See also PHP RFC: Static variables in inherited methods.
1.2.578.1. Connex PHP features¶
1.2.578.1.1. Suggestions¶
Define the method in the child class to enforce the distinct behavior
Replace the static variable by a static property to make this PHP 8.1 ready
1.2.578.1.2. Specs¶
Short name |
Variables/InheritedStaticVariable |
Rulesets |
|
Exakat since |
2.2.2 |
PHP Version |
With PHP 8.0 and older |
Severity |
Minor |
Time To Fix |
Quick (30 mins) |
Changed Behavior |
PHP 8.1 |
Precision |
Medium |
Available in |