Autoloading Classes
What Is Autoloading?
In simple terms: Without autoloading, every file that uses a class must first require the file that defines it. In a project with hundreds of classes, these lists of require statements become long, fragile, and easy to get wrong. Autoloading lets PHP load a class file automatically the first time the class is used.
Technically: When PHP encounters a class, interface, trait, or enum that has not been defined yet, it calls the autoloader functions registered with spl_autoload_register(), passing the fully qualified class name. An autoloader translates that name into a file path and includes the file. In practice, almost every PHP project uses the autoloader generated by Composer, following the PSR-4 standard.
Without vs With Autoloading
// Without autoloading
require __DIR__ . '/src/Models/User.php';
require __DIR__ . '/src/Models/Order.php';
require __DIR__ . '/src/Services/Greeter.php';
// ... and many more, in the right order
// With autoloading
require __DIR__ . '/vendor/autoload.php';
// every class is loaded on demand
| Benefit | Explanation |
|---|---|
| Less code | No manual require lists |
| Only what is needed | Classes are loaded when first used, not all at startup |
| No ordering problems | Dependencies load themselves when referenced |
| Standard structure | Class names map predictably to file paths |
The PSR-4 Convention
PSR-4 defines how class names map to files:
Namespace prefix App\ → base directory src/
Class App\Models\User
Relative name Models\User → file src/Models/User.php
Rules:
- A namespace prefix (such as
App 0 ) is mapped to a **base directory** (such assrc/`). - The rest of the class name becomes the path: namespace separators