rfc:static_variable_inheritance
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
rfc:static_variable_inheritance [2021/02/23 13:45] – created nikic | rfc:static_variable_inheritance [2021/04/28 15:12] (current) – nikic | ||
---|---|---|---|
Line 2: | Line 2: | ||
* Date: 2021-02-23 | * Date: 2021-02-23 | ||
* Author: Nikita Popov < | * Author: Nikita Popov < | ||
- | * Status: | + | * Status: |
* Target Version: PHP 8.1 | * Target Version: PHP 8.1 | ||
+ | * Implementation: | ||
===== Introduction ===== | ===== Introduction ===== | ||
Line 28: | Line 29: | ||
When '' | When '' | ||
- | This RFC proposed | + | This RFC proposes |
<PHP> | <PHP> | ||
Line 145: | Line 146: | ||
var_dump(B:: | var_dump(B:: | ||
var_dump(B:: | var_dump(B:: | ||
+ | </ | ||
+ | |||
+ | The behavior does not depend on whether the method is static or not: | ||
+ | |||
+ | <PHP> | ||
+ | class A { | ||
+ | public function counter() { | ||
+ | static $i = 0; | ||
+ | return ++$i; | ||
+ | } | ||
+ | } | ||
+ | class B extends A {} | ||
+ | |||
+ | var_dump((new A)-> | ||
+ | var_dump((new A)-> | ||
+ | var_dump((new B)-> | ||
+ | var_dump((new B)-> | ||
</ | </ | ||
Line 168: | Line 186: | ||
</ | </ | ||
- | This is consistent with the general semantics of traits as " | + | This is consistent with the general semantics of traits as " |
===== Backward Incompatible Changes ===== | ===== Backward Incompatible Changes ===== | ||
- | The behavior of static variables in methods changes as described above. The current behavior of static variables is not documented. I consider it to be borderline buggy. | + | The behavior of static variables in methods changes as described above. The current behavior of static variables is not documented. I consider it to be borderline buggy. Typical memoization use-cases for static variables will not be affected (apart from memoizing more effectively). |
+ | |||
+ | Code that intentionally relies on the current behavior can be made compatible by indexing the static variable by the class name: | ||
+ | |||
+ | < | ||
+ | class A { | ||
+ | public function counter() { | ||
+ | // This code works both for static and non-static methods. | ||
+ | static $counters = []; | ||
+ | $counters[static:: | ||
+ | return ++$counters[static:: | ||
+ | } | ||
+ | } | ||
+ | class B extends A { | ||
+ | } | ||
+ | |||
+ | var_dump((new A)-> | ||
+ | var_dump((new A)-> | ||
+ | var_dump((new B)-> | ||
+ | var_dump((new B)-> | ||
+ | </ | ||
+ | |||
+ | This code will work the same way both before and after the proposed behavior change. | ||
===== Vote ===== | ===== Vote ===== | ||
- | Yes/No. | + | Voting started 2021-04-14 and ended 2021-04-28. |
+ | |||
+ | <doodle title=" | ||
+ | | ||
+ | | ||
+ | </ |
rfc/static_variable_inheritance.1614087950.txt.gz · Last modified: 2021/02/23 13:45 by nikic