PHP Autoloading
In this page:
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
// Without autoloading: require 'User.php'; require 'Product.php'; ...
echo "Autoloading loads a class file automatically the first time it's used";
?>
Login to try C/C++/Java/PHP code in the editor
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
spl_autoload_register(function ($class) {
echo "Would load file for class: $class\n";
});
class_exists("SomeUndefinedClass");
?>
Login to try C/C++/Java/PHP code in the editor
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
spl_autoload_register(function ($class) {
$file = $class . '.php';
echo "Looking for file: $file\n";
});
class_exists("User");
?>
Login to try C/C++/Java/PHP code in the editor
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
spl_autoload_register(function ($class) {
$path = str_replace('\\', '/', $class) . '.php';
echo "Resolved path: $path\n";
});
class_exists("App\\Models\\User");
?>
Login to try C/C++/Java/PHP code in the editor
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
// composer.json: "autoload": { "psr-4": { "App\\": "src/" } }
echo "Composer maps the App\\ namespace to the src/ folder automatically";
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 24 topics to unlock
0/24 topics done
Complete these topics first:
- PHP Date & Time
- PHP Math Functions
- PHP JSON Handling
- PHP XML Handling
- PHP cURL Introduction
- PHP REST API Basics
- PHP Composer & Packages
- PHP Autoloading
- PHP Design Patterns
- PHP MVC Architecture
- PHP Security Best Practices
- PHP Performance Optimization
- PHP 8 New Features
- PHP Type Declarations
- PHP Match Expression Advanced
- PHP Fibers
- PHP Attributes
- PHP Magic Constants
- PHP Include & Require
- PHP Iterables
- PHP SimpleXML Parser
- PHP SimpleXML Get
- PHP XML Expat Parser
- PHP DOM Parser