Guides

Lazy Loading in PHP

February 23, 2014

Here’s the canonical method of lazy loading of an object attribute.

The point of lazy loading is when some attribute of an object is another object, and its construction is costly. As the result, we don’t want to create this another object at the time of creating the parent object. Only at the time when we really need this object.

So:

class Lazyloader
{
  private $huge;
  
  public function getHuge()
  {
    if (!$this->huge)
      $this->huge = $this->makeHuge();

    return $this->huge;
  }
  
  public function makeHuge()
  {
    // ... actual creation of the child object ...
  }
}

It’s not Haskell, of course, but this idiom is quite simple and more importantly, you can add lazyloading to any attribute, even already existing.

Previous: Making Websites With YiiBoilerplate Next: How to setup Lisp development in Windows