3v4l.org

run code in 300+ PHP versions simultaneously
<?php class MyEnum { private $values = [ 'A' => 1, 'B' => 2, 'C' => 3, ]; private $key = null; public function __construct($key) { if (!isset($this->values[$key])) { throw new Exception('Incorrect Enum Value'); } $this->key = $key; } public function key(): string { return $this->key; } public function val(): int { return $this->values[$this->key]; } } function foo(MyEnum $foo) { echo $foo->val().PHP_EOL; } // This works foo(new MyEnum('A')); try { // Rejected, don't allow passing the underlying value foo(1); } catch (\Throwable $e) { echo $e->getMessage().PHP_EOL; } try { // Rejected, value not part of the enum foo(new MyEnum('D')); } catch (\Throwable $e) { echo $e->getMessage().PHP_EOL; }
Output for 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
1 foo(): Argument #1 ($foo) must be of type MyEnum, int given, called in /in/bBpRu on line 39 Incorrect Enum Value
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 1 foo(): Argument #1 ($foo) must be of type MyEnum, int given, called in /in/bBpRu on line 39 Incorrect Enum Value
Output for 7.3.0 - 7.3.33, 7.4.0 - 7.4.33
1 Argument 1 passed to foo() must be an instance of MyEnum, int given, called in /in/bBpRu on line 39 Incorrect Enum Value
Output for 7.1.0 - 7.1.33, 7.2.0 - 7.2.33
1 Argument 1 passed to foo() must be an instance of MyEnum, integer given, called in /in/bBpRu on line 39 Incorrect Enum Value
Output for 5.6.38
Parse error: syntax error, unexpected ':', expecting ';' or '{' in /in/bBpRu on line 21
Process exited with code 255.

preferences:
183.69 ms | 401 KiB | 203 Q