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

PHP Autoloading

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) {
    echo "Would load file for class: $class\n";
});
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) {
    $file = $class . '.php';
    echo "Looking for file: $file\n";
});
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) {
    $path = str_replace('\\', '/', $class) . '.php';
    echo "Resolved path: $path\n";
});
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";
?>

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.