Sitemap

Member-only story

Dependency Injection with PHP 8.4’s Lazy Objects

5 min readJan 21, 2025

--

PHP 8.4 is out now for approximately 2 month and there are a lot of new features. One significant new feature is “Lazy Objects”, which is described as follows:

A lazy object is an object whose initialization is deferred until its state is observed or modified.

The past few weeks, I read a couple of blogs addressing Lazy Objects in the context of Dependency Injection and how it works together to boost up performance. I would like to discuss a few confusions and clarify some terminology.

⚠️ Note on Thread Safety

The container example shown here is intentionally simplified to illustrate lazy initialization. In a standard PHP environment (like FPM or CLI), this pattern works as expected. However, in multi-threaded or asynchronous runtimes (e.g. Swoole, ReactPHP), you must account for potential race conditions. The example is not thread-safe in such contexts.

For production-ready implementations in concurrent environments, consider using proper synchronization mechanisms or thread-safe containers — and avoid double-checked locking, which is known to be unreliable due to memory model issues.

This topic will also be published as a video on my YouTube channel: https://www.youtube.com/@doganoo

I will go into the topic in more detail there. So don’t forget to follow so you don’t miss anything!

--

--

Doğan Uçar
Doğan Uçar

Written by Doğan Uçar

Software Engineer, PHP/Laminas (Zend), Backend, Cloud, Freelancer & CEO, Open Source Contributor

Responses (1)