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 git.master_jit, git.master
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.

This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.

Active branches

Archived branches

Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page


preferences:
54.72 ms | 406 KiB | 5 Q