3v4l.org

run code in 300+ PHP versions simultaneously
<?php final readonly class Post { public int $id; public string $name; public string $email; public function greet(): string { return "Hello 👋"; } } final readonly class PostRepository { private ReflectionClass $reflector; public function __construct( ) { $this->reflector = new ReflectionClass(Post::class); } public function find(int $id): Post { var_dump("Loading post with ID $id"); $entity = $this->reflector->newLazyGhost(function ($entity) use ($id) { var_dump("Lazy initialization triggered for ID $id"); $data = $this->loadFromDatabase($id); $this->reflector->getProperty('name')->setValue($entity, $data['name']); $this->reflector->getProperty('email')->setValue($entity, $data['email']); }); // ID is already known and can be accessed without triggering initialization $this->reflector->getProperty('id')->setRawValueWithoutLazyInitialization($entity, $id); return $entity; } private function loadFromDatabase(int $id): array { // Simulate loading from database return [ 'name' => 'John Doe', 'email' => 'john.doe@example.com', ]; } } $em = new PostRepository(); $post = $em->find(42); var_dump($post); var_dump($post->greet()); // This will really trigger the lazy initialization $post->email; var_dump($post);
Output for 8.4.1 - 8.4.14, 8.5.0
string(23) "Loading post with ID 42" lazy ghost object(Post)#4 (1) { ["id"]=> int(42) ["name"]=> uninitialized(string) ["email"]=> uninitialized(string) } string(10) "Hello 👋" string(39) "Lazy initialization triggered for ID 42" object(Post)#4 (3) { ["id"]=> int(42) ["name"]=> string(8) "John Doe" ["email"]=> string(20) "john.doe@example.com" }
Output for 8.4.15
/bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libm.so.6: version `GLIBC_2.35' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.34' not found (required by /bin/php-8.4.15) /bin/php-8.4.15: /usr/lib/libc.so.6: version `GLIBC_2.38' not found (required by /bin/php-8.4.15)
Process exited with code 1.
Output for 8.2.23 - 8.2.29, 8.3.5 - 8.3.28
string(23) "Loading post with ID 42" Fatal error: Uncaught Error: Call to undefined method ReflectionClass::newLazyGhost() in /in/XNRiS:28 Stack trace: #0 /in/XNRiS(53): PostRepository->find(42) #1 {main} thrown in /in/XNRiS on line 28
Process exited with code 255.
Output for 8.1.30 - 8.1.33
Parse error: syntax error, unexpected token "readonly", expecting "abstract" or "final" or "class" in /in/XNRiS on line 3
Process exited with code 255.

preferences:
84.74 ms | 410 KiB | 5 Q