Last active
June 21, 2020 22:12
-
-
Save ramiror/deec982e3db0226e3586d948945cac90 to your computer and use it in GitHub Desktop.
Simplest PHP enum I could make -- a tradeoff between features and complexity
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 | |
| // pais.php | |
| class Pais { | |
| private function __construct() {} | |
| static private $instance; | |
| static function register() { | |
| assert(self::$instance, 'Uninitialized Pais enum'); | |
| $name = get_called_class(); | |
| echo "registering $name\n"; | |
| self::$instance->{$name} = new $name(); | |
| } | |
| static function get() { | |
| assert(self::$instance, 'Uninitialized Pais enum'); | |
| return clone self::$instance; | |
| } | |
| static function init() { | |
| self::$instance = new self(); | |
| } | |
| function getUrl() { | |
| throw new Exception('Not implemented'); | |
| } | |
| } | |
| Pais::init(); | |
| function Pais() { | |
| return Pais::get(); | |
| } | |
| // argentina.php | |
| class Argentina extends Pais { | |
| function getUrl() { | |
| return 'AAA'; | |
| } | |
| } | |
| Argentina::register(); | |
| // uruguay.php | |
| class Uruguay extends Pais { | |
| function getUrl() { | |
| return 'UUU'; | |
| } | |
| } | |
| Uruguay::register(); | |
| // cliente.php | |
| class Cliente { | |
| function getBaseUrl(Pais $pais) { | |
| return $pais->getUrl(); | |
| } | |
| } | |
| $cliente = new Cliente(); | |
| echo 'Argentina usa ' . $cliente->getBaseUrl(Pais()->Argentina) . PHP_EOL; | |
| echo 'Uruguay usa ' . $cliente->getBaseUrl(Pais()->Uruguay) . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment