Home » Php » php – Lazy loading? Is it better to avoid it?

php – Lazy loading? Is it better to avoid it?

Posted by: admin July 12, 2020 Leave a comment


I just read about the “lazy loading” design pattern.

Is it ok to overuse lazy loading to load all classes and forget about include(..) entirely?
What are the cons of this approach?

How to&Answers:

A couple points on autoloading:

  1. You will see a nice performance
    improvement by using autoloading
    versus always including all of your
    files all the time
    (especially as the number of files
    grows larger and larger).

  2. When implementing autoloading, it is
    better to use
    spl_autoload_register() than

Although a lot of times when people talk about lazy loading in PHP, they are talking about something like the following:

class Foo {
    protected $bar = null;

    public function getBar() {
        if ($this->bar == null) {
            $this->bar = ExpensiveOperation();
        return $this->bar;

Then you only load a property when it actually needs to be used, and not every time you instantiate the object, which can potentially have some good benefits.


One benefit of a lazy loader is that it only loads the class files that are actually needed by the script during the course of its execution, potentially saving memory; when otherwise you might include all class files, whether they are needed or not. Depending on your scripts, this can make quite a difference.


It is fine to use explicit includes, or to have __autoload() find your classes for you. Either way.

I wouldn’t recommend mixing the two strategies, though. The include lines would be unnecessary.