1--TEST-- 2Lazy objects: Lazy entity loading 3--FILE-- 4<?php 5 6class User { 7 private string $transient; 8 9 public function __construct( 10 private int $id, 11 private string $name, 12 ) { 13 } 14 15 public function getId(): int { 16 return $this->id; 17 } 18 19 public function getName(): string { 20 return $this->name; 21 } 22} 23 24class EntityManager { 25 public function lazyLoad(string $fqcn, int $id): object { 26 $reflector = new ReflectionClass($fqcn); 27 $entity = $reflector->newLazyGhost(function ($obj) { 28 var_dump('initializer'); 29 $prop = new ReflectionProperty($obj::class, 'name'); 30 $prop->setValue($obj, 'John Doe'); 31 }); 32 33 (new ReflectionProperty($fqcn, 'id'))->setRawValueWithoutLazyInitialization($entity, $id); 34 35 return $entity; 36 } 37} 38 39$em = new EntityManager(); 40$user = $em->lazyLoad(User::class, 123); 41 42printf("Fetching identifier does not trigger initializer\n"); 43var_dump($user->getId()); 44 45printf("Fetching anything else triggers initializer\n"); 46var_dump($user->getName()); 47--EXPECTF-- 48Fetching identifier does not trigger initializer 49int(123) 50Fetching anything else triggers initializer 51string(11) "initializer" 52string(8) "John Doe" 53