← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 8 of 24

PHP Autoloading

Autoloading is like a librarian who fetches a book only at the moment you need it. PHP loads a class file automatically when your code first uses that class.
Syntax
php
spl_autoload_register(function ($class) {
    require __DIR__ . "/" . $class . ".php";   // one class per file
});

$object = new ClassName();   // file loaded automatically

What is Autoloading?

Autoloading lets PHP load a class file automatically the first time that class is actually used, eliminating the tedious block of require statements older codebases needed at the top of every file.

Example: What is Autoloading?

php
<?php
// Without autoloading: require 'User.php'; require 'Product.php'; ...
echo "Autoloading loads a class file automatically the first time it's used";
?>

The spl_autoload_register() function

spl_autoload_register() registers a callback function that PHP invokes whenever code references a class it hasn't loaded yet, giving you full control over how class names map to file paths.

Example: The spl_autoload_register() function

php
<?php
spl_autoload_register(function ($class) {
    // Print "Would load file for class: $class\n" to the output
    echo "Would load file for class: $class\n";
});
// Call `class_exists("SomeUndefinedClass")`
class_exists("SomeUndefinedClass");
?>

Structuring Folders for Autoloading

A common convention pairs one class per file, named to match the class exactly (User.php contains class User), which makes it trivial for an autoloader to guess the right file from just the class name.

Example: Structuring Folders for Autoloading

php
<?php
spl_autoload_register(function ($class) {
    // Declare `$file`, set to `$class . '.php'`
    $file = $class . '.php';
    // Print "Looking for file: $file\n" to the output
    echo "Looking for file: $file\n";
});
// Call `class_exists("User")`
class_exists("User");
?>

Autoloading with Namespaces

When classes live inside namespaces, the autoloader receives the fully-qualified name (like App\Models\User); converting the backslashes to slashes gives you a relative file path to require.

Example: Autoloading with Namespaces

php
<?php
spl_autoload_register(function ($class) {
    // Declare `$path`, set to `str_replace('\\', '/', $class) . '.php'`
    $path = str_replace('\\', '/', $class) . '.php';
    // Print "Resolved path: $path\n" to the output
    echo "Resolved path: $path\n";
});
// Call `class_exists("App\\Models\\User")`
class_exists("App\\Models\\User");
?>

PSR-4 Autoloading Standard

PSR-4 formalizes that namespace-to-folder mapping as a standard every PHP package can rely on, which is why modern projects rarely write a custom autoloader by hand anymore -- Composer handles it via PSR-4 configuration.

Example: PSR-4 Autoloading Standard

php
<?php
// composer.json: "autoload": { "psr-4": { "App\\": "src/" } }
echo "Composer maps the App\\ namespace to the src/ folder automatically";
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using file names or paths that do not match the class name and namespace, so the autoloader cannot find the class.
  2. Forgetting to register the autoloader with spl_autoload_register before using a class.
  3. Getting the case wrong on case-sensitive file systems, such as user.php for a class User.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.