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
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.

preferences:
155.52 ms | 1395 KiB | 8 Q