1--TEST--
2Lazy objects: json_encode initializes object
3--FILE--
4<?php
5
6#[AllowDynamicProperties]
7class C {
8    public int $a;
9    public int $b {
10        get { return $this->b; }
11        set(int $value) { $this->b = $value; }
12    }
13    public int $c {
14        get { return $this->a + 2; }
15    }
16    public function __construct() {
17        var_dump(__METHOD__);
18        $this->a = 1;
19        $this->b = 2;
20        $this->d = 4;
21    }
22}
23
24$reflector = new ReflectionClass(C::class);
25
26print "# Ghost:\n";
27
28$obj = $reflector->newLazyGhost(function ($obj) {
29    var_dump("initializer");
30    $obj->__construct();
31});
32
33var_dump(json_encode($obj));
34
35print "# Proxy:\n";
36
37$obj = $reflector->newLazyProxy(function ($obj) {
38    var_dump("initializer");
39    return new C();
40});
41
42var_dump(json_encode($obj));
43
44print "# Ghost (init exception):\n";
45
46$obj = $reflector->newLazyGhost(function ($obj) {
47    throw new \Exception();
48});
49
50try {
51    var_dump(json_encode($obj));
52} catch (\Exception $e) {
53    printf("%s: %s\n", $e::class, $e->getMessage());
54}
55
56print "# Proxy (init exception):\n";
57
58$obj = $reflector->newLazyProxy(function ($obj) {
59    throw new \Exception();
60});
61
62try {
63    var_dump(json_encode($obj));
64} catch (\Exception $e) {
65    printf("%s: %s\n", $e::class, $e->getMessage());
66}
67
68--EXPECT--
69# Ghost:
70string(11) "initializer"
71string(14) "C::__construct"
72string(25) "{"a":1,"b":2,"c":3,"d":4}"
73# Proxy:
74string(11) "initializer"
75string(14) "C::__construct"
76string(25) "{"a":1,"b":2,"c":3,"d":4}"
77# Ghost (init exception):
78Exception:
79# Proxy (init exception):
80Exception:
81