PHP autoload: spl_autoload_register() and Composer
Autoloading loads a class's file at the moment the code first uses it: no more lines of require_once to line up, and no more loading order to respect.
spl_autoload_register(function (string $classe): void { $prefixe = 'Gazette\\'; if (!str_starts_with($classe, $prefixe)) { return; // not a gazette class: another autoloader will take care of it } $fichier = __DIR__ . '/../src/' . str_replace('\\', '/', substr($classe, strlen($prefixe))) . '.php'; if (is_file($fichier)) { require $fichier; } }); $article = new Gazette\Article('The pumpkin festival'); // src/Article.php is loaded here
When PHP meets a class it doesn't know, it calls the functions registered with spl_autoload_register(), one by one, before throwing “Class not found”. Each one receives the full class name, namespace included, and loads the right file if it knows where to find it. So a class is only loaded if it is used, and a class added to src/ is available without declaring anything.
In a real project, you no longer write this function yourself: the “namespace prefix to folder” rule is called PSR-4, and Composer generates it in vendor/autoload.php, the only file you still load by hand. The classic traps: a file name that doesn't exactly match the class name (case matters on Linux, but not on macOS or Windows by default: code that works on your Mac breaks on the Linux server), and an autoload rule changed in composer.json without running composer dump-autoload again.
4 exercises work on this concept, by writing code in the browser.
In the tracks
- My first autoloader Learn PHP 8 from scratch · chapter 3: Too many requires
- Namespaces Learn PHP 8 from scratch · chapter 3: Too many requires
- Declaring PSR-4 Learn PHP 8 from scratch · chapter 4: Composer takes over
- Goodbye, homemade autoloader Learn PHP 8 from scratch · chapter 4: Composer takes over