Intermediate LevelPHP 8+
How do you build a custom PSR-4 autoloader from scratch using spl_autoload_register() without Composer?
❓ Interview Prompt: Explain spl_autoload_register(), namespace-to-filepath mapping algorithms, and building lightweight custom autoloaders.
Before Composer, PHP developers registered custom autoloader callbacks using 'spl_autoload_register()'.
How Custom PSR-4 Autoloading Works:
1
Register a callback with 'spl_autoload_register($callback)'.
2
When a class is instantiated ('new AppServicesPaymentService()'), PHP passes the fully qualified class name to the callback.
3
The callback converts namespace separators ('') to directory slashes ('/'), appends '.php', and calls 'require' if the file exists!
Code Implementation Example
php
<?php
// Custom PSR-4 Autoloader from scratch
spl_autoload_register(function (string $class): void {
$prefix = 'App\';
$baseDir = __DIR__ . '/src/';
// Check if class uses the 'App\' namespace prefix
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) return;
// Get relative class name and map namespace separators to directory slashes
$relativeClass = substr($class, $len);
$file = $baseDir . str_replace('\', '/', $relativeClass) . '.php';
if (file_exists($file)) {
require $file;
}
});💡Building a custom PSR-4 class autoloader using spl_autoload_register().
🎯 Interview Key Takeaway
spl_autoload_register() registers custom callback functions to dynamically load class files when instantiated.
#spl_autoload_register#Autoloading#PSR-4#Intermediate
Back to all PHP 8+ Questions→