Reputation: 76280
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?
Upvotes: 7
Views: 2754
Reputation: 8003
A couple points on autoloading:
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).
When implementing autoloading, it is
better to use
spl_autoload_register()
than
__autoload()
.
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.
Upvotes: 8
Reputation: 212452
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.
Upvotes: 3
Reputation: 98509
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.
Upvotes: 2