Using Weak References to Improve Efficiency

As PHP continues to grow and mature, more and more developers are turning to PHP frameworks to facilitate rapid application development. A necessary by-product of this practice, however, is ever larger and more complex objects occupying memory. Large objects that contain many properties, other objects, or sizeable arrays are often referred to as expensive objects.

Compounding the potential memory issues caused by this trend is the fact that all PHP object assignments are automatically made by reference. Without references, the use of third-party frameworks would become cumbersome in the extreme. When we assign an object by reference, however, the object must remain in memory, in its entirety, until all references are destroyed. Only then, after unsetting or overwriting the object, is it entirely destroyed.

In PHP 7.4, a potential solution to this problem was introduced in the form of weak reference support. PHP 8 expanded upon this new ability by adding a weak map class. We’ll learn how this new technology works and how it can prove advantageous to development. Let’s first have a look at weak references.

Taking advantage of weak references

Weak references were first introduced in PHP 7.4 and have been refined in PHP 8. This class serves as a wrapper for object creation that allows the developer to use references to objects in such a manner whereby out-of-scope (for example, unset()) objects are not protected from garbage collection.

There are a number of PHP extensions currently residing on pecl.php.net that provide support for weak references. Most of the implementations hack into the C-language structures of the PHP language core and either overload object handlers or manipulate the stack and various C pointers. The net result, in most cases, is a loss of portability and lots of segmentation faults. The PHP 8 implementation avoids these problems.

It’s important to master the use of PHP 8 weak references if we are working on program code that involves large objects and where the program code might run for a long time. Before getting into usage details, let’s have a look at the class definition.

Reviewing the WeakReference class definition

The formal definition for the WeakReference class is as follows:

Get hands-on with 1200+ tech skills courses.