0Pricing
PHP Academy · Lesson

Registering Autoloaders

Set up spl_autoload_register and Composer-based autoloading.

spl_autoload_register

spl_autoload_register() registers a callback PHP calls whenever an undefined class is used. Multiple autoloaders run in registration order.

Basic Custom Autoloader

A minimal PSR-4-style autoloader written by hand:

<?php
spl_autoload_register(function (string $class): void {
    $prefix  = 'App\\';
    $baseDir = __DIR__.'/src/';
    if (!str_starts_with($class, $prefix)) return;
    $rel  = substr($class, strlen($prefix));
    $file = $baseDir.str_replace('\\', '/', $rel).'.php';
    if (file_exists($file)) require $file;
});

All lessons in this course

  1. Declaring and Using Namespaces
  2. Nested Namespaces and Aliases
  3. PSR-4 Autoloading Standard
  4. Registering Autoloaders
← Back to PHP Academy