Last active
June 26, 2023 09:57
-
-
Save gabesullice/543d89c33cc569d69cd9518659223166 to your computer and use it in GitHub Desktop.
self vs static vs $this
This file contains 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 ParentClass { | |
public static string $foo = 'ooh'; | |
public string $bar = 'lala'; | |
public function __construct($arg) { | |
$this->bar = $arg; | |
} | |
public function dump(): void { | |
printf( | |
"Class: %s\nself::\$foo: %s\nstatic::\$foo: %s\n\$this::\$foo: %s\n\$this->bar: %s" . PHP_EOL, | |
static::class, | |
self::$foo, | |
static::$foo, | |
$this::$foo, | |
$this->bar, | |
); | |
} | |
} | |
class ChildClass extends ParentClass { | |
public static string $foo = 'ahh'; | |
public string $bar = 'haha'; | |
} | |
$parent = new ParentClass('parent'); | |
$child = new ChildClass('child'); | |
$parent->dump(); | |
echo PHP_EOL; | |
$child->dump(); | |
echo PHP_EOL; | |
echo "Setting ParentClass::\$foo = 'hmm'" . PHP_EOL; | |
ParentClass::$foo = 'hmm'; | |
echo PHP_EOL; | |
$parent->dump(); | |
echo PHP_EOL; | |
$child->dump(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Prints: