1--TEST--
2Lazy objects: RFC example 004
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    $blogPost->title = $data['title'];
29    $blogPost->content = $data['content'];
30};
31$post = $reflector->newLazyGhost($initializer);
32
33// Without this line, the following call to ReflectionProperty::setValue() would trigger initialization.
34$reflector->getProperty('id')->skipLazyInitialization($post);
35$reflector->getProperty('id')->setValue($post, 123);
36
37// Alternatively, one can use this directly:
38$reflector->getProperty('id')->setRawValueWithoutLazyInitialization($post, 123);
39
40var_dump($post);
41var_dump($post->id);
42var_dump($post->title);
43var_dump($post->content);
44var_dump($post);
45
46?>
47==DONE==
48--EXPECTF--
49lazy ghost object(BlogPost)#%d (1) {
50  ["id"]=>
51  int(123)
52  ["title"]=>
53  uninitialized(string)
54  ["content"]=>
55  uninitialized(string)
56}
57int(123)
58string(14) "initialization"
59string(5) "Title"
60string(7) "Content"
61object(BlogPost)#%d (3) {
62  ["id"]=>
63  int(123)
64  ["title"]=>
65  string(5) "Title"
66  ["content"]=>
67  string(7) "Content"
68}
69==DONE==
70