Use Lazy Objects in PHP 8.4

Use Lazy Objects in PHP 8.4

Since PHP 8.4, lazy objects can be utilized to defer an object's initialization until it is actually accessed. This technique reduces resource consumption, particularly for objects with complex initialization logic that might not always be needed during execution.

Let's say we have the following class:

Person.php

<?php

class Person
{
    public function __construct(private string $name)
    {
        echo 'Created'.PHP_EOL;
    }

    public function getName(): string
    {
        return $this->name;
    }
}

In the following code, the Person constructor is invoked immediately upon object creation:

<?php

require_once 'Person.php';

$person = new Person('John');

echo 'Accessing object'.PHP_EOL;
echo $person->getName().PHP_EOL;
Created
Accessing object
John

Lazy objects utilize a dynamically generated proxy to delay the execution of the target object's constructor. This proxy, created using reflection, mimics the original class, keeping the actual object uninitialized until it is accessed.

In the example below, the newLazyGhost method creates a lazy object. The constructor is invoked, and the object is initialized when the getName method is called.

<?php

require_once 'Person.php';

$reflector = new ReflectionClass(Person::class);
$person = $reflector->newLazyGhost(function (Person $person): void {
    $person->__construct('John');
});

echo 'Accessing object'.PHP_EOL;
echo $person->getName().PHP_EOL;
Accessing object
Created
John

Delayed instantiation with lazy objects reduces memory usage and enhances performance. Developers can work with lazy objects just like regular ones. This approach is especially beneficial in scenarios like dependency injection containers, ORM systems, or other services, where initialization can be deferred until necessary.

Leave a Comment

Cancel reply

Your email address will not be published.