Without autoloading, you need a require line for every class file. With 200 classes, that is a mess, and a missing line causes an error at run time.
Autoloading lets PHP load a class file on demand: the first time your code uses a class, PHP calls a function that you provide, and that function finds and loads the file.
spl_autoload_register()
<?php
spl_autoload_register(function (string $class): void {
echo "Autoloader asked for: $class\n";
});
class_exists("Missing\\Thing"); // triggers the autoloader
echo "Done";
Autoloader asked for: Missing\Thing
Done
PHP gives your function the fully qualified class name. Your job is to load the file that defines it.
A simple autoloader
Suppose your classes use the namespace App\ and live in src/. The class App\Service\Greeter should be in src/Service/Greeter.php.
<?php
namespace App\Service;
class Greeter
{
public function hello(string $name): string
{
return "Hello, $name";
}
}
<?php
spl_autoload_register(function (string $class): void {
$prefix = "App\\";
if (!str_starts_with($class, $prefix)) {
return; // not one of ours
}
$relative = substr($class, strlen($prefix));
$file = __DIR__ . "/src/" . str_replace("\\", "/", $relative) . ".php";
if (is_file($file)) {
require $file;
}
});
use App\Service\Greeter;
echo (new Greeter())->hello("Ana");
Hello, Ana
The steps:
new Greeter()needs the class. PHP does not know it yet.- PHP calls the autoloader with
App\Service\Greeter. - The autoloader removes the
App\prefix, turns\into/and adds.php. - It finds
src/Service/Greeter.phpand requires it.
Why it is better
- No list of
requirelines to maintain. - A class is loaded only if it is used, so unused code costs nothing.
- Adding a new class only means creating a file in the right place.
Several autoloaders
You can register more than one. PHP calls them in order until the class exists. That is how Composer’s autoloader and your own can work together.
Always check the prefix and the file
A real autoloader must be defensive: ignore classes that are not yours, and check that the file exists. Never build a path from a class name you did not expect.
Autoloading and interfaces, traits, enums
Autoloading works for classes, interfaces, traits and enums alike.
You rarely write this yourself
This is the idea behind Composer’s autoloader. You will use Composer’s version in practice. The next lesson gives the standard that makes this work everywhere: PSR-4.
Do not use __autoload()
__autoload() was an older function and has been removed from PHP 8. Use spl_autoload_register().