1--TEST--
2Lazy objects: RFC example 012
3--FILE--
4<?php
5
6// User code
7
8class ClientFactory
9{
10    public function __construct(
11        private string $hostname,
12        private string $credentials,
13    ) {}
14
15    public function createClient() {
16        return new Client($this->hostname, $this->credentials);
17    }
18}
19
20class Client
21{
22    public function __construct(
23        private string $hostname,
24        private string $credentials,
25    ) {}
26
27    public function doSomething()
28    {
29        printf("doSomething() (hostname: %s)\n", $this->hostname);
30    }
31}
32
33// Symfony code
34
35class Container
36{
37    public function getClientFactoryService(): ClientFactory
38    {
39        return new ClientFactory('127.0.0.1', 'secret');
40    }
41
42    public function getClientService(): Client
43    {
44        $reflector = new ReflectionClass(Client::class);
45
46        $client = $reflector->newLazyProxy(function () {
47            $clientFactory = $this->getClientFactoryService();
48            return $clientFactory->createClient();
49        });
50
51        return $client;
52    }
53}
54
55$container = new Container();
56$service = $container->getClientService();
57var_dump($service);
58$service->doSomething();
59var_dump($service);
60
61?>
62==DONE==
63--EXPECTF--
64lazy proxy object(Client)#%d (0) {
65  ["hostname":"Client":private]=>
66  uninitialized(string)
67  ["credentials":"Client":private]=>
68  uninitialized(string)
69}
70doSomething() (hostname: 127.0.0.1)
71lazy proxy object(Client)#%d (1) {
72  ["instance"]=>
73  object(Client)#%d (2) {
74    ["hostname":"Client":private]=>
75    string(9) "127.0.0.1"
76    ["credentials":"Client":private]=>
77    string(6) "secret"
78  }
79}
80==DONE==
81