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

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:
43.28 ms | 406 KiB | 5 Q