3v4l.org

run code in 300+ PHP versions simultaneously
<?php readonly class ValidAge { private const MINIMUM_AGE = 10; private function __construct(public int $age) {} public static function createFromInt(int $age): self|NotValidAge { if (self::MINIMUM_AGE >= $age) { return new NotValidAge($age, 'Too old'); } return new self($age); } } readonly class NotValidAge { public function __construct( public int $age, public string $error ) {} } class ValidateAge { public function __invoke(int $age): ValidAge|NotValidAge { return ValidAge::createFromInt($age); } } class User { public function __construct( public int $id, public ValidAge $age ) {} } $rawAge = 33; $age = (new ValidateAge)($rawAge); $user = new User(1, $age); var_dump($user); $wrongAge = 8; $notValidAge = (new ValidateAge)($wrongAge); $anotherUser = new User(1, $notValidAge); var_dump($anotherUser);
Output for 8.2.13 - 8.2.29, 8.3.5 - 8.3.25, 8.4.1 - 8.4.12
object(User)#1 (2) { ["id"]=> int(1) ["age"]=> object(ValidAge)#2 (1) { ["age"]=> int(33) } } Fatal error: Uncaught TypeError: User::__construct(): Argument #2 ($age) must be of type ValidAge, NotValidAge given, called in /in/WksJS on line 46 and defined in /in/WksJS:32 Stack trace: #0 /in/WksJS(46): User->__construct(1, Object(NotValidAge)) #1 {main} thrown in /in/WksJS on line 32
Process exited with code 255.
Output for 8.1.30 - 8.1.33
Parse error: syntax error, unexpected token "readonly", expecting end of file in /in/WksJS on line 3
Process exited with code 255.

preferences:
57.68 ms | 407 KiB | 5 Q