3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Bar { public function __construct( public Bar $bar, public int $x, public bool $main = false, ) {} public function withMain(): self { $clone = clone $this; $clone->main = true; return $clone; } } class Fiz { public Bar|null $cache = null; public function foo(int $i) { if (!$this->cache) { $this->cache = $this->factor($i); } if ($i <= 1) { return $this ->cache ->withMain(); } return $this->cache; } public function factor(int $i): object { $reflector = new ReflectionClass(Bar::class); return $reflector->newLazyGhost( function (Bar $bar) use ($i) { $bar->__construct($this->foo($i + 1), 2); }, ); } } $fiz = new Fiz(); $f = $fiz->foo(0); var_dump($f->bar->bar->x);
Output for 8.4.1 - 8.4.14
Fatal error: Uncaught Error: Typed property Bar::$bar must not be accessed before initialization in /in/lYpu1:51 Stack trace: #0 {main} thrown in /in/lYpu1 on line 51
Process exited with code 255.
Output for 8.2.0 - 8.2.29, 8.3.0 - 8.3.26
Fatal error: Uncaught Error: Call to undefined method ReflectionClass::newLazyGhost() in /in/lYpu1:40 Stack trace: #0 /in/lYpu1(24): Fiz->factor(0) #1 /in/lYpu1(50): Fiz->foo(0) #2 {main} thrown in /in/lYpu1 on line 40
Process exited with code 255.

preferences:
72.9 ms | 407 KiB | 5 Q