Last active
December 18, 2019 14:55
-
-
Save GuyPaddock/23009aa481c9e0422b00639810b9ba1c to your computer and use it in GitHub Desktop.
How Static Variables Work with Inheritance in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
On PHP 7.2.24-0ubuntu0.18.04.1 (cli) (built: Oct 28 2019 12:07:07) ( NTS ): | |
ClassA = 1576680836 | |
ClassA = 1576680836 | |
ClassA = 1576680838 | |
ClassA = 1576680838 | |
ClassA = 1576680840 | |
ClassA = 1576680840 | |
ClassX = 1576680842 | |
ClassX = 1576680842 | |
ClassA = 1576680844 | |
ClassA = 1576680844 | |
ClassY = 1576680846 | |
ClassY = 1576680846 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ClassA { | |
function test1() { | |
static $x = NULL; | |
if (empty($x)) { | |
$x = time(); | |
} | |
print __CLASS__ . " = " . $x . "\n"; | |
} | |
function test2() { | |
static $x = NULL; | |
if (empty($x)) { | |
$x = time(); | |
} | |
print __CLASS__ . " = " . $x . "\n"; | |
} | |
} | |
class ClassX extends ClassA { | |
function test2() { | |
static $x = NULL; | |
if (empty($x)) { | |
$x = time(); | |
} | |
print __CLASS__ . " = " . $x . "\n"; | |
} | |
} | |
class ClassY extends ClassA { | |
function test2() { | |
static $x = NULL; | |
if (empty($x)) { | |
$x = time(); | |
} | |
print __CLASS__ . " = " . $x . "\n"; | |
} | |
} | |
(new ClassA())->test1(); | |
sleep(1); | |
(new ClassA())->test1(); | |
sleep(1); | |
(new ClassA())->test2(); | |
sleep(1); | |
(new ClassA())->test2(); | |
sleep(1); | |
print "\n"; | |
(new ClassX())->test1(); | |
sleep(1); | |
(new ClassX())->test1(); | |
sleep(1); | |
(new ClassX())->test2(); | |
sleep(1); | |
(new ClassX())->test2(); | |
sleep(1); | |
print "\n"; | |
(new ClassY())->test1(); | |
sleep(1); | |
(new ClassY())->test1(); | |
sleep(1); | |
(new ClassY())->test2(); | |
sleep(1); | |
(new ClassY())->test2(); | |
sleep(1); | |
print "\n"; | |
print "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment