1--TEST--
2Lazy objects: RFC example 005
3--FILE--
4<?php
5
6class BlogPost
7{
8    public function __construct(
9        public int $id,
10        public string $title,
11        public string $content,
12    ) {
13    }
14}
15
16function loadFromDB() {
17    return [
18        'title' => 'Title',
19        'content' => 'Content',
20    ];
21}
22
23$reflector = new ReflectionClass(BlogPost::class);
24// Callable that retrieves the title and content from the database.
25$initializer = function ($blogPost) {
26    var_dump("initialization");
27    $data = loadFromDB();
28    return new BlogPost($blogPost->id, $data['title'], $data['content']);
29};
30$post = $reflector->newLazyProxy($initializer);
31
32// Without this line, the following call to ReflectionProperty::setValue() would trigger initialization.
33$reflector->getProperty('id')->skipLazyInitialization($post);
34$reflector->getProperty('id')->setValue($post, 123);
35
36// Alternatively, one can use this directly:
37$reflector->getProperty('id')->setRawValueWithoutLazyInitialization($post, 123);
38
39var_dump($post);
40var_dump($post->id);
41var_dump($post->title);
42var_dump($post->content);
43var_dump($post);
44
45?>
46==DONE==
47--EXPECTF--
48lazy proxy object(BlogPost)#%d (1) {
49  ["id"]=>
50  int(123)
51  ["title"]=>
52  uninitialized(string)
53  ["content"]=>
54  uninitialized(string)
55}
56int(123)
57string(14) "initialization"
58string(5) "Title"
59string(7) "Content"
60lazy proxy object(BlogPost)#%d (1) {
61  ["instance"]=>
62  object(BlogPost)#%d (3) {
63    ["id"]=>
64    int(123)
65    ["title"]=>
66    string(5) "Title"
67    ["content"]=>
68    string(7) "Content"
69  }
70}
71==DONE==
72