Autoloading classes

As you already know, in order to use a class, you need to include the file that defines it. So far, we have been including the files manually, as we only had a couple of classes and used them in one file. But what happens when we use several classes in several files? There must be a smarter way, right? Indeed there is. Autoloading to the rescue!

Autoloading is a PHP feature that allows your program to search and load files automatically given some set of predefined rules. Each time you reference a class that PHP does not know about, it will ask the autoloader. If the autoloader can figure out which file that class is in, it will load it, and the execution of the program will continue as normal. If it does not, PHP will stop ...

Get Learning PHP 7 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.