3v4l.org

run code in 300+ PHP versions simultaneously
<?php readonly class Name implements Stringable { public function __construct( public string $value ) { if (strlen($value) === 0) { throw new ValueError("Name must be non-empty"); } } public function __toString(): string { return $this->value; } } readonly class User { public function __construct( public Name $name, // if we are receiving a Name instance, it just means that it's already a valid value! ) { } } $user1 = new User( new Name('Some valid name') ); echo $user1->name; // "Some valid name" $user2 = new User( new Name('') // kaboom );
Output for 8.2.11 - 8.2.25, 8.3.5 - 8.3.14
Some valid name Fatal error: Uncaught ValueError: Name must be non-empty in /in/QWm8c:9 Stack trace: #0 /in/QWm8c(34): Name->__construct('') #1 {main} thrown in /in/QWm8c on line 9
Process exited with code 255.
Output for 8.1.30
Parse error: syntax error, unexpected token "readonly", expecting end of file in /in/QWm8c on line 3
Process exited with code 255.

preferences:
49.56 ms | 407 KiB | 5 Q