spl_autoload_register
Registers a function that loads a class file the first time the class is used.
Syntax
spl_autoload_register(?callable $callback = null, bool $throw = true, bool $prepend = false): boolParameters
| Parameter | Type | Description |
|---|---|---|
| $callback | ?callable | A function that receives the class name. |
| $throw | bool | Optional. Unused since PHP 8. |
| $prepend | bool | Optional. Put the function first in the queue. |
Return value
bool`true` if the function was registered.
Examples
The autoloader receives the class name:
<?php
spl_autoload_register(function (string $class) {
echo 'Loading ', $class, "\n";
});
var_dump(class_exists('App\\Models\\User'));Output:
Loading App\Models\User
bool(false)Notes
Writing an autoloader by hand is rarely needed: Composer generates one — just include vendor/autoload.php.
See also
- class_exists — Checks whether a class is defined.
In the tutorial
- Namespaces and Composer — How a PHP project is organised — namespaces, PSR-4 class autoloading and installing libraries with Composer.