note 124708 added to language.variables.scope

From: Date: Wed, 12 Feb 2020 04:32:35 +0000
Subject: note 124708 added to language.variables.scope
Groups: php.notes 
Request: Send a blank email to php-notes+get-214081@lists.php.net to get a copy of this message
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 ---- Server IP: 45.112.84.4 Probable Submitter: 38.142.137.34 (proxied: 58.96.17.165) ---- Manual Page -- http://php.net/manual/en/language.variables.scope.php Edit -- https://master.php.net/note/edit/124708 Del: integrated -- https://master.php.net/note/delete/124708/integrated Del: useless -- https://master.php.net/note/delete/124708/useless Del: bad code -- https://master.php.net/note/delete/124708/bad+code Del: spam -- https://master.php.net/note/delete/124708/spam Del: non-english -- https://master.php.net/note/delete/124708/non-english Del: in docs -- https://master.php.net/note/delete/124708/in+docs Del: other reasons-- https://master.php.net/note/delete/124708 Reject -- https://master.php.net/note/reject/124708 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#214081) next »