3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Foo { private $foo; private $lazyLoad; public function saySomething() { return 'Saying ' . $this->foo; } private function __construct() { } public static function new() : self { $instance = new self(); $instance->foo = 'something'; return $instance; } public static function newLazy() : self { $instance = new self(); $instance->lazyLoad = function () use ($instance) { $instance->foo = 'something lazy'; }; unset($instance->foo); return $instance; } public function __get($name) { ($this->lazyLoad)(); return $this->foo; } } $foo = Foo::new(); var_dump($foo->saySomething()); $lazyFoo = Foo::newLazy(); var_dump($lazyFoo->saySomething());

preferences:
26.14 ms | 404 KiB | 5 Q