Lazy objects

suggest change

A lazy object looks and behaves like a normal instance of its class, but its state is created only when the object is actually used. Until then it costs almost nothing: no database connection, no parsed configuration file, no SQL query.

Libraries have done this for years by generating proxy subclasses with code generators (Doctrine proxies, ocramius/proxy-manager, Symfony's VarExporter). PHP 8.4 builds lazy objects into the engine, and you create them with the Reflection API:

This article covers:

All examples need PHP 8.4 or newer. They were run with PHP 8.5.

Related topics: Composition and delegation (has a short lazy proxy example), Reflection, Container Injection and Property hooks.

A first lazy ghost

newLazyGhost() takes an initializer: a closure that receives the lazy object and fills in its properties. Calling the constructor on it is the simplest way to do that:

<?php
class AppConfig
{
    public array $settings;

    public function __construct(public string $file)
    {
        echo "  parsing $file...\n";
        // imagine a slow parse of a big file here
        $this->settings = ['debug' => true, 'locale' => 'en_US'];
    }

    public function describe(): string
    {
        return 'application configuration';
    }
}

$class = new ReflectionClass(AppConfig::class);
$config = $class->newLazyGhost(function (AppConfig $ghost) {
    echo "  initializer called\n";
    $ghost->__construct('config/app.ini');
});

echo "created\n";
var_dump($config instanceof AppConfig);
echo $config->describe(), "\n";
var_dump($class->isUninitializedLazyObject($config));

echo "reading a property\n";
echo $config->settings['locale'], "\n";
var_dump($class->isUninitializedLazyObject($config));
echo $config->file, "\n";

Output:

created
bool(true)
application configuration
bool(true)
reading a property
  initializer called
  parsing config/app.ini...
en_US
bool(false)
config/app.ini

The object is created by Reflection, not by new, so the class itself needs no changes. Lazy objects are an infrastructure feature for frameworks and libraries. Application code keeps using the class as usual.

What triggers initialization

Initialization is triggered by anything that reads or writes the object's state, its properties. Operations on the object's identity or type don't trigger it:

<?php
class Point
{
    public function __construct(public int $x = 0, public int $y = 0) {}
}

$class = new ReflectionClass(Point::class);
$make = fn() => $class->newLazyGhost(function (Point $p) {
    $p->__construct(3, 4);
});

$operations = [
    'var_dump'        => fn($p) => var_dump($p),
    'get_class'       => fn($p) => get_class($p),
    'spl_object_id'   => fn($p) => spl_object_id($p),
    '(array) cast'    => fn($p) => (array) $p,
    'read $p->x'      => fn($p) => $p->x,
    'write $p->x'     => fn($p) => $p->x = 1,
    'isset($p->x)'    => fn($p) => isset($p->x),
    'foreach'         => function ($p) { foreach ($p as $v) {} },
    'get_object_vars' => fn($p) => get_object_vars($p),
    'json_encode'     => fn($p) => json_encode($p),
    'serialize'       => fn($p) => serialize($p),
    'clone'           => fn($p) => clone $p,
];

foreach ($operations as $name => $op) {
    $p = $make();
    ob_start();
    $op($p);
    ob_end_clean();
    $state = $class->isUninitializedLazyObject($p) ? 'still lazy' : 'initialized';
    printf("%-16s %s\n", $name, $state);
}

Output:

var_dump         still lazy
get_class        still lazy
spl_object_id    still lazy
(array) cast     still lazy
read $p->x       initialized
write $p->x      initialized
isset($p->x)     initialized
foreach          initialized
get_object_vars  initialized
json_encode      initialized
serialize        initialized
clone            initialized

Watch out for the (array) cast: on an uninitialized lazy object it doesn't trigger initialization, it returns an empty array:

<?php
class Point
{
    public function __construct(public int $x = 0, public int $y = 0) {}
}
$class = new ReflectionClass(Point::class);
$p = $class->newLazyGhost(fn(Point $p) => $p->__construct(3, 4));
var_dump((array) $p);
var_dump($class->isUninitializedLazyObject($p));
var_dump(get_object_vars($p));

Output:

array(0) {
}
bool(true)
array(2) {
  ["x"]=>
  int(3)
  ["y"]=>
  int(4)
}

Use get_object_vars() instead of an (array) cast when the object could be lazy.

Lazy proxies

A ghost requires that you can initialize the object in place, typically by calling its constructor. Sometimes the object has to come from somewhere else: a static factory method, a builder, or another library. In that case use newLazyProxy(). Its initializer is a factory that returns the real instance:

<?php
class HttpClient
{
    public function __construct(private string $baseUrl, private int $timeout)
    {
        echo "  creating client for $baseUrl\n";
    }

    public function get(string $path): string
    {
        return "GET {$this->baseUrl}{$path} (timeout {$this->timeout}s)";
    }

    public static function fromEnv(array $env): self
    {
        return new self($env['API_URL'], (int) $env['API_TIMEOUT']);
    }
}

$env = ['API_URL' => 'https://api.example.com', 'API_TIMEOUT' => '5'];

$class = new ReflectionClass(HttpClient::class);
$client = $class->newLazyProxy(function (HttpClient $proxy) use ($env): HttpClient {
    echo "  factory called\n";
    return HttpClient::fromEnv($env);
});

echo "proxy created\n";
var_dump($client);
echo $client->get('/users'), "\n";
echo $client->get('/orders'), "\n";
var_dump($client);

Output:

proxy created
lazy proxy object(HttpClient)#3 (0) {
  ["baseUrl":"HttpClient":private]=>
  uninitialized(string)
  ["timeout":"HttpClient":private]=>
  uninitialized(int)
}
  factory called
  creating client for https://api.example.com
GET https://api.example.com/users (timeout 5s)
GET https://api.example.com/orders (timeout 5s)
lazy proxy object(HttpClient)#3 (1) {
  ["instance"]=>
  object(HttpClient)#4 (2) {
    ["baseUrl":"HttpClient":private]=>
    string(23) "https://api.example.com"
    ["timeout":"HttpClient":private]=>
    int(5)
  }
}

Ghost or proxy?

Lazy ghost Lazy proxy
Created by newLazyGhost($initializer) newLazyProxy($factory)
The callback fills in the object it receives returns a new real instance
After initialization the ghost is the object the proxy forwards to a separate object
Identity only one object exists two objects: proxy and real instance
Use when you control how the object is constructed the object comes from a factory or another library

Prefer ghosts when you can. They're slightly cheaper, and they avoid the identity problem described next.

Proxy identity

A proxy and its real instance are two different objects. Methods called on the proxy run with $this set to the proxy, and their property accesses are forwarded to the real instance. That works fine until the real instance leaks out, for example when its constructor stores $this somewhere:

<?php
class EventBus
{
    public static array $listeners = [];
}

class AuditLog
{
    public array $entries = [];

    public function __construct()
    {
        // the constructor leaks $this: this is the REAL instance
        EventBus::$listeners[] = $this;
    }

    public function self(): static
    {
        return $this;
    }
}

$class = new ReflectionClass(AuditLog::class);
$log = $class->newLazyProxy(fn(AuditLog $proxy) => new AuditLog());

$log->entries[] = 'login';             // triggers the factory
$real = $class->initializeLazyObject($log);

var_dump($log === $real);              // proxy and real are different objects
var_dump($log->self() === $log);       // methods run with $this = proxy
var_dump(EventBus::$listeners[0] === $log);
var_dump(EventBus::$listeners[0] === $real);

// state is shared: property access on the proxy is forwarded
$real->entries[] = 'logout';
print_r($log->entries);
var_dump($log == $real);

Output:

bool(false)
bool(true)
bool(false)
bool(true)
Array
(
    [0] => login
    [1] => logout
)
bool(true)

If identity matters, use a ghost. With a ghost, the constructor's $this is the lazy object itself.

Use case: lazy services in a DI container

A dependency injection container builds an object graph: a controller needs a repository, the repository needs a database connection. Without laziness, building the controller connects to the database even when the current request never runs a query. Here a tiny container wraps services marked lazy in a proxy:

<?php
final class Container
{
    private array $factories = [];
    private array $lazy = [];
    private array $instances = [];

    public function set(string $id, Closure $factory, bool $lazy = false): void
    {
        $this->factories[$id] = $factory;
        $this->lazy[$id] = $lazy;
    }

    public function get(string $id): object
    {
        if (isset($this->instances[$id])) {
            return $this->instances[$id];
        }
        $factory = $this->factories[$id];
        if ($this->lazy[$id]) {
            $object = new ReflectionClass($id)
                ->newLazyProxy(fn() => $factory($this));
        } else {
            $object = $factory($this);
        }
        return $this->instances[$id] = $object;
    }
}

class Database
{
    public function __construct(private string $dsn)
    {
        echo "  connecting to $dsn\n";
    }

    public function query(string $sql): array
    {
        echo "  [{$this->dsn}] $sql\n";
        return [['id' => 1, 'name' => 'Ada']];
    }
}

class UserRepository
{
    public function __construct(private Database $db) {}

    public function all(): array
    {
        return $this->db->query('SELECT * FROM users');
    }
}

class HomeController
{
    public function __construct(private UserRepository $users) {}

    public function index(): string { return 'Welcome!'; }

    public function users(): string
    {
        return count($this->users->all()) . ' user(s)';
    }
}

$c = new Container();
$c->set(Database::class, fn() => new Database('sqlite::memory:'), lazy: true);
$c->set(UserRepository::class, fn(Container $c) => new UserRepository($c->get(Database::class)));
$c->set(HomeController::class, fn(Container $c) => new HomeController($c->get(UserRepository::class)));

$controller = $c->get(HomeController::class);
foreach (['index', 'users'] as $action) {
    echo "action: $action\n";
    $body = $controller->$action();
    echo "  -> $body\n";
}

Output:

action: index
  -> Welcome!
action: users
  connecting to sqlite::memory:
  [sqlite::memory:] SELECT * FROM users
  -> 1 user(s)

A proxy fits here because the container only has a factory closure, not a way to call the constructor on an existing object. Recent Symfony versions use native lazy objects for lazy: true services when running on PHP 8.4+. See Container Injection for more on containers.

Use case: ORM references and properties set without initialization

An ORM often knows an entity's primary key long before it needs the rest of the row: a post row contains author_id = 7, but loading the author is a second query. A ghost can hold the known id while the other properties stay lazy. ReflectionProperty::setRawValueWithoutLazyInitialization() sets a property without triggering the initializer:

<?php
class Author
{
    public int $id;
    public string $name;
    public string $email;
}

class Post
{
    public function __construct(
        public int $id,
        public string $title,
        public Author $author,
    ) {}
}

// a fake database table
$authorsTable = [
    7 => ['name' => 'Ada Lovelace', 'email' => 'ada@example.com'],
];

final class EntityManager
{
    private ReflectionClass $authorClass;
    private array $identityMap = [];

    public function __construct(private array $table)
    {
        $this->authorClass = new ReflectionClass(Author::class);
    }

    public function authorReference(int $id): Author
    {
        if (isset($this->identityMap[$id])) {
            return $this->identityMap[$id];
        }
        $author = $this->authorClass->newLazyGhost(function (Author $a) {
            echo "  SELECT * FROM authors WHERE id = {$a->id}\n";
            $row = $this->table[$a->id];
            $a->name = $row['name'];
            $a->email = $row['email'];
        });
        // the id is known without a query: set it without initializing
        $this->authorClass->getProperty('id')
            ->setRawValueWithoutLazyInitialization($author, $id);

        return $this->identityMap[$id] = $author;
    }

    public function isLoaded(object $entity): bool
    {
        return !$this->authorClass->isUninitializedLazyObject($entity);
    }
}

$em = new EntityManager($authorsTable);
$posts = [
    new Post(1, 'Notes on the Analytical Engine', $em->authorReference(7)),
    new Post(2, 'Bernoulli numbers', $em->authorReference(7)),
];

foreach ($posts as $post) {
    echo "{$post->title} (author #{$post->author->id})\n";
}
var_dump($em->isLoaded($posts[0]->author));
var_dump($posts[0]->author === $posts[1]->author);

echo "by {$posts[0]->author->name}\n";
echo "by {$posts[1]->author->name} <{$posts[1]->author->email}>\n";
var_dump($em->isLoaded($posts[1]->author));

Output:

Notes on the Analytical Engine (author #7)
Bernoulli numbers (author #7)
bool(false)
bool(true)
  SELECT * FROM authors WHERE id = 7
by Ada Lovelace
by Ada Lovelace <ada@example.com>
bool(true)

Doctrine ORM 3.4+ can build its entity proxies this way on PHP 8.4 (an opt-in setting), without generating proxy classes.

skipLazyInitialization and initializeLazyObject

ReflectionProperty::skipLazyInitialization() marks a property as not lazy and gives it its default value. Use it for flags or counters that make sense before the object is loaded. ReflectionClass::initializeLazyObject() forces initialization without touching a property:

<?php
class Report
{
    public bool $dirty = false;
    public array $rows;

    public function __construct()
    {
        echo "  running expensive query\n";
        $this->rows = [10, 20, 30];
    }
}

$class = new ReflectionClass(Report::class);
$report = $class->newLazyGhost(fn(Report $r) => $r->__construct());

// $dirty has a default value: let it be used without initializing
$class->getProperty('dirty')->skipLazyInitialization($report);

var_dump($report->dirty);
$report->dirty = true;
var_dump($class->isUninitializedLazyObject($report));

// force initialization explicitly
$same = $class->initializeLazyObject($report);
var_dump($same === $report);
echo array_sum($report->rows), "\n";
var_dump($report->dirty);

Output:

bool(false)
bool(true)
  running expensive query
bool(true)
60
bool(true)

markLazyObjectAsInitialized

markLazyObjectAsInitialized() does the opposite of initializeLazyObject(): it marks the object as initialized without calling the initializer. Properties that are still lazy get their default values, and properties without a default stay uninitialized:

<?php
class Counter
{
    public int $count = 0;
    public string $label = 'clicks';
}

$class = new ReflectionClass(Counter::class);
$c = $class->newLazyGhost(function (Counter $c) {
    echo "  initializer\n";
    $c->count = 100;
});

$class->markLazyObjectAsInitialized($c);  // initializer is NOT called
var_dump($class->isUninitializedLazyObject($c));
var_dump($c);

Output:

bool(false)
object(Counter)#3 (2) {
  ["count"]=>
  int(0)
  ["label"]=>
  string(6) "clicks"
}

This is useful when you find out that the initializer isn't needed after all, for example because the entity was just created and has nothing to load.

getLazyInitializer($object) returns the initializer of an uninitialized lazy object, or null once it has been initialized.

When the initializer fails

If the initializer throws, PHP reverts the object to its uninitialized lazy state, discarding the properties the initializer had set before the exception. The next access tries again:

<?php
class Settings
{
    public array $values;
}

$attempt = 0;
$class = new ReflectionClass(Settings::class);
$settings = $class->newLazyGhost(function (Settings $s) use (&$attempt) {
    $attempt++;
    echo "  attempt $attempt\n";
    if ($attempt === 1) {
        throw new RuntimeException('settings server unavailable');
    }
    $s->values = ['theme' => 'dark'];
});

try {
    echo $settings->values['theme'], "\n";
} catch (RuntimeException $e) {
    echo "error: ", $e->getMessage(), "\n";
}
var_dump($class->isUninitializedLazyObject($settings));

echo $settings->values['theme'], "\n";
var_dump($class->isUninitializedLazyObject($settings));

Output:

  attempt 1
error: settings server unavailable
bool(true)
  attempt 2
dark
bool(false)

There's no half-initialized object to worry about. Either the initializer finished, or the object is still lazy.

Making an existing object lazy again

resetAsLazyGhost() and resetAsLazyProxy() turn an already constructed object into a lazy one. Its properties are discarded, but the object keeps its identity, so every reference to it sees the reloaded state. An ORM uses this to refresh an entity from the database:

<?php
class Product
{
    public function __construct(
        public int $id,
        public string $name,
        public int $price,
    ) {}
}

// pretend this is the database
$db = [3 => ['name' => 'Keyboard', 'price' => 4900]];

$product = new Product(3, 'Keyboard', 4900);
$product->price = 1;  // an unsaved local change

$class = new ReflectionClass(Product::class);

// throw away the in-memory state and reload on next access
$class->resetAsLazyGhost($product, function (Product $p) use (&$db) {
    echo "  reloading product {$p->id}\n";
    $row = $db[$p->id];
    $p->__construct($p->id, $row['name'], $row['price']);
});
$class->getProperty('id')->setRawValueWithoutLazyInitialization($product, 3);

$db[3]['price'] = 5900;  // someone changed it in the database

var_dump($class->isUninitializedLazyObject($product));
echo "{$product->name}: {$product->price}\n";

Output:

bool(true)
  reloading product 3
Keyboard: 5900

Serialization

serialize() initializes a lazy object so that the full state is written. Pass ReflectionClass::SKIP_INITIALIZATION_ON_SERIALIZE to serialize the object as it is instead (a lazy object then serializes as if it had no properties):

<?php
class Session
{
    public array $data;
}

$class = new ReflectionClass(Session::class);
$init = function (Session $s) {
    $s->data = ['user' => 'ada'];
};

$a = $class->newLazyGhost($init);
echo serialize($a), "\n";
var_dump($class->isUninitializedLazyObject($a));

$b = $class->newLazyGhost($init, ReflectionClass::SKIP_INITIALIZATION_ON_SERIALIZE);
echo serialize($b), "\n";
var_dump($class->isUninitializedLazyObject($b));

Output:

O:7:"Session":1:{s:4:"data";a:1:{s:4:"user";s:3:"ada";}}
bool(false)
O:7:"Session":0:{}
bool(true)

Unserializing always creates a normal, non-lazy object.

Pitfalls

Initializer mistakes

An arrow function returns the value of its expression, and an initializer must return null. If the initializer forgets to set a typed property, the access that triggered it fails anyway:

<?php
class Settings
{
    public array $values;
}

$class = new ReflectionClass(Settings::class);

// arrow functions return the value of their expression
$s = $class->newLazyGhost(fn(Settings $s) => $s->values = ['a' => 1]);
try {
    $s->values;
} catch (TypeError $e) {
    echo $e->getMessage(), "\n";
}

// the initializer forgot to set a typed property
$s = $class->newLazyGhost(function (Settings $s) {});
try {
    $s->values;
} catch (Error $e) {
    echo $e->getMessage(), "\n";
}

Output:

Lazy object initializer must return NULL or no value
Typed property Settings::$values must not be accessed before initialization

Use a function () { ... } block for initializers that assign properties. fn($o) => $o->__construct(...) is fine because constructors return nothing.

Internal classes can't be lazy

Classes implemented in C, and user classes that extend them, can't be made lazy. The only exception is stdClass. A proxy factory must return an object of a compatible class:

<?php
class ArrayCollection extends ArrayObject {}

foreach ([ArrayCollection::class, DateTimeImmutable::class, stdClass::class] as $name) {
    try {
        new ReflectionClass($name)->newLazyGhost(function ($o) {});
        echo "$name: ok\n";
    } catch (Error $e) {
        echo $e->getMessage(), "\n";
    }
}

class Order { public int $id; }

$class = new ReflectionClass(Order::class);
$proxy = $class->newLazyProxy(fn() => new stdClass());
try {
    $proxy->id;
} catch (TypeError $e) {
    echo substr($e->getMessage(), 0, 82), "...\n";
}

Output:

Cannot make instance of internal class lazy: ArrayCollection inherits internal class ArrayObject
Cannot make instance of internal class lazy: DateTimeImmutable is internal
stdClass: ok
The real instance class stdClass is not compatible with the proxy class Order. The...

So you can't make an ArrayObject, PDO, DateTime or Exception subclass lazy. Wrap it in a user class and make that class lazy instead.

What works fine

Some things that block code-generated proxies aren't a problem for native lazy objects:

<?php
final readonly class Connection
{
    public function __construct(public string $dsn)
    {
        echo "  open $dsn\n";
    }

    public function __destruct()
    {
        echo "  close {$this->dsn}\n";
    }
}

$class = new ReflectionClass(Connection::class);

$used = $class->newLazyGhost(function (Connection $c) {
    $c->__construct('mysql:host=primary');
});
$unused = $class->newLazyGhost(function (Connection $c) {
    $c->__construct('mysql:host=replica');
});

echo $used->dsn, "\n";
unset($used, $unused);
echo "done\n";

Output:

  open mysql:host=primary
mysql:host=primary
  close mysql:host=primary
done

The replica connection was never opened, so it's never closed either.

Don't make everything lazy

A lazy object only pays off when creating the object is expensive and some code paths never use it. For cheap objects the lazy wrapper is pure overhead. Initialization also happens at a hard-to-predict place, the first property access, so errors like "connection refused" show up far from the code that wired the object. Keep laziness inside infrastructure code like containers and ORMs, and keep application classes unaware of it.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents