3v4l.org

run code in 300+ PHP versions simultaneously
<?php abstract class Enum { private $name; protected $allow = []; private static $enums; private function __construct($name) { if (!in_array($name, $this->allow, true)) { throw new \TypeError('Undefined enum ' . get_class($this) . '::' . $name . '()'); } $this->name = $name; } public static function __callStatic($name, $args) { $id = static::class . ".$name"; return self::$enums[$id] ?? self::$enums[$id] = new static($name); } public function __toString() { return $this->name; } } /** * @method static RED() * @method static GREEN() * @method static BLUE() */ class Color extends Enum { protected $allow = ['RED', 'GREEN', 'BLUE']; } $red = Color::RED(); $red2 = Color::RED(); $green = Color::GREEN(); var_dump($red === $red2); var_dump($red == $red2); var_dump($red === $green); var_dump($red == $green); var_dump((string) $red); var_dump((string) $green); $geern = Color::GEERN(); // Intentional typo. Throws.

preferences:
76.46 ms | 402 KiB | 5 Q