Lazy Objects

Lazy objects is a application of lazy-loading, directly applied in the PHP engine, and available as an engine feature since PHP 8.4.

The traditional way to create an object is to use new. The object is immediately created, and then, accessed later if needed.

Lazy objects defer the actual instantiation of the object until it is actually accessed. Nothing happens until the object is used. In the case of large applications, where lots of services or assets are created systematically, lazy objects postpone initialization, and may even skip it entirely if it is not needed.

Lazy objects are good for objects that takes a lot of resources to initialize, or when there are lots of such objects, with a good proportion of them not being used, in the end.

<?php

    // taken from the RFC (https://wiki.php.net/rfc/lazy-objects)
    class MyClass
    {
        public function __construct(private int $foo)
        {
            // Heavy initialization logic here.
        }

        // ...
    }

    $initializer = static function (MyClass $ghost): void {
        $ghost->__construct(123);
    };

    $reflector = new ReflectionClass(MyClass::class);
    $object = $reflector->newLazyGhost($initializer);

    // At this point, $object is a lazy ghost object.

?>

Documentation

See also Lazy objects in PHP 8.4, Using PHP 8.4’s Lazy Objects and PHP Object Lazy-Loading is More Than What You Think.

Related : Lazy Loading, Class, Proxy Class, Proxy