Created
September 29, 2025 11:27
-
-
Save adamcameron/9cd7ed4403368f1329d97eaea6de2077 to your computer and use it in GitHub Desktop.
Demonstrating using static to refer to the "current" class when using inheritance
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 TranslatedNumber { | |
| function __construct(protected int $number, protected string $en, protected $mi){} | |
| function getAll(){ | |
| return ['number' => $this->number, 'en' => $this->en, 'mi' => $this->mi]; | |
| } | |
| static function fromArray($a) { | |
| return new static(...$a); // HERE | |
| } | |
| } | |
| $tahi = new TranslatedNumber(1, "one", "tahi"); | |
| var_dump($tahi->getAll()); | |
| $rua = TranslatedNumber::fromArray([2, "two", "rua"]); | |
| var_dump($rua->getAll()); | |
| class ShoutyTranslatedNumber extends TranslatedNumber { | |
| function __construct(int $number, string $en, string $mi) { | |
| parent::__construct($number, strtoupper($en), strtoupper($mi)); | |
| } | |
| } | |
| $toru = new ShoutyTranslatedNumber(3, "three", "toru"); | |
| var_dump($toru->getAll()); | |
| $wha = ShoutyTranslatedNumber::fromArray([4, "four", "wha"]); | |
| var_dump($wha->getAll()); | |
| var_dump([ | |
| 'tahi' => get_class($tahi), | |
| 'rua' => get_class($rua), | |
| 'toru' => get_class($toru), | |
| 'wha' => get_class($wha), | |
| ]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment