Registering Autoloaders
Set up spl_autoload_register and Composer-based autoloading.
spl_autoload_register
spl_autoload_register() registers a callback PHP calls whenever an undefined class is used. Multiple autoloaders run in registration order.
Basic Custom Autoloader
A minimal PSR-4-style autoloader written by hand:
<?php
spl_autoload_register(function (string $class): void {
$prefix = 'App\\';
$baseDir = __DIR__.'/src/';
if (!str_starts_with($class, $prefix)) return;
$rel = substr($class, strlen($prefix));
$file = $baseDir.str_replace('\\', '/', $rel).'.php';
if (file_exists($file)) require $file;
});All lessons in this course
- Declaring and Using Namespaces
- Nested Namespaces and Aliases
- PSR-4 Autoloading Standard
- Registering Autoloaders