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.
Output for 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.30, 8.0.0 - 8.0.20, 8.1.0 - 8.1.7
bool(true) bool(true) bool(false) bool(false) string(3) "RED" string(5) "GREEN" Fatal error: Uncaught TypeError: Undefined enum Color::GEERN() in /in/aoPUl:9 Stack trace: #0 /in/aoPUl(16): Enum->__construct('GEERN') #1 /in/aoPUl(44): Enum::__callStatic('GEERN', Array) #2 {main} thrown in /in/aoPUl on line 9
Process exited with code 255.
Output for 5.6.0 - 5.6.40
Parse error: syntax error, unexpected '?' in /in/aoPUl on line 16
Process exited with code 255.

preferences:
52.01 ms | 410 KiB | 5 Q