Autoloading classes with spl_autoload_register in PHP
Stop writing require lines: map class names to files and let PHP load them on demand.
This guide revisits and updates an original tutorial from noiretaya.com (
log.noiretaya.com/191). The code has been refreshed for current versions.Register an autoloader
spl_autoload_register() takes a callback that PHP calls whenever an unknown class is referenced. Map the class name to a file and require it.
spl_autoload_register(function ($class) {
$file = __DIR__ . '/src/' . str_replace('\\', '/', $class) . '.php';
if (is_file($file)) {
require $file;
}
});
With this in place, new App\Mailer\SmtpClient() loads src/App/Mailer/SmtpClient.php automatically — no manual includes.
PSR-4 in practice
This is exactly what Composer does. In real projects, declare it in composer.json and let Composer generate the autoloader.
{
"autoload": {
"psr-4": { "App\\": "src/" }
}
}
composer dump-autoload
Rule of thumb: one class per file, file path mirrors the namespace. Hand-rolled autoloaders are great for learning; ship Composer's PSR-4 autoloader in production.