1--TEST--
2Lazy objects: Lazy service initialization in dependency injection container
3--FILE--
4<?php
5
6class EntityManager {
7    public function __construct() {
8        var_dump(__METHOD__);
9    }
10}
11
12class Application {
13    public function __construct(
14        private EntityManager $em,
15    ) {
16        var_dump(__METHOD__);
17    }
18
19    public function doSomethingWithEntityManager()
20    {
21    }
22}
23
24class Container {
25    public function getEntityManagerService(): EntityManager {
26        $reflector = new ReflectionClass(EntityManager::class);
27        $obj = $reflector->newLazyGhost(function ($obj) {
28            $obj->__construct();
29        });
30        return $obj;
31    }
32
33    public function getApplicationService(): Application {
34        return new Application($this->getEntityManagerService());
35    }
36}
37
38$container = new Container();
39
40printf("Service can be fetched without initializing dependencies\n");
41$application = $container->getApplicationService();
42--EXPECTF--
43Service can be fetched without initializing dependencies
44string(24) "Application::__construct"
45