Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

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): bool

Parameters

ParameterTypeDescription
$callback?callableA function that receives the class name.
$throwboolOptional. Unused since PHP 8.
$prependboolOptional. 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

In the tutorial

  • Namespaces and Composer — How a PHP project is organised — namespaces, PSR-4 class autoloading and installing libraries with Composer.

Thanks for reading!

Donate to the site — we work hard for you.