As PHP applications grow, you'll usually organize your classes into separate files. However, manually loading every class with require can quickly become difficult to manage.
PHP autoloading solves this problem by automatically loading class files when they're needed.
In this guide, you'll learn how autoloading works, how to create a basic autoloader, and how to use Composer with the PSR-4 standard.
What Is Autoloading in PHP?
Without autoloading, you must load a class file before using the class.
<?php
require __DIR__ . "/src/Content/Article.php";
$article = new /App/Content/Article("PHP Basics");
This approach works for small projects, but larger applications may contain dozens or hundreds of classes.
With autoloading, PHP can locate and load the required class automatically.
Instead of manually loading each file, you configure an autoloader once and use classes normally throughout your application.
How Does PHP Autoloading Work?
When PHP encounters a class that hasn't been loaded, it can call registered autoload functions to locate the corresponding class definition.
PHP provides the function spl_autoload_register() to register an autoloader.
The process works like this:
- Your code attempts to use a class.
- PHP checks whether that class is already available.
- If necessary, PHP calls registered autoload functions.
- An autoloader attempts to locate and include the class file.
- PHP continues using the class if it becomes available.
If the class still cannot be found, PHP reports an error.
Creating a Simple PHP Autoloader
Let's create an autoloader that loads classes from a src directory.
First, create this project structure:
my-project/
index.php
src/
Content/
Article.php
Step 1: Create the Article Class
Open src/Content/Article.php:
<?php
namespace App/Content;
class Article
{
public function __construct(
private string $title
) {
}
public function getTitle(): string
{
return $this->title;
}
}
The class belongs to the App/Content namespace.
Step 2: Register the Autoloader
Open index.php:
<?php
declare(strict_types=1);
spl_autoload_register(function (string $class): void {
$prefix = "App//";
$baseDirectory = __DIR__ . "/src/";
// Only handle classes in the App namespace.
if (!str_starts_with($class, $prefix)) {
return;
}
// Remove the namespace prefix.
$relativeClass = substr(
$class,
strlen($prefix)
);
// Convert namespace separators into directory separators.
$file = $baseDirectory
. str_replace("//", "/", $relativeClass)
. ".php";
// Load the class if its file exists.
if (is_file($file)) {
require $file;
}
});
// Use the class without manually requiring its file.
$article = new /App/Content/Article(
"Learning PHP Autoloading"
);
echo htmlspecialchars(
$article->getTitle(),
ENT_QUOTES,
"UTF-8"
);
Output:
Learning PHP Autoloading
The autoloader translates App/Content/Article into the filesystem path src/Content/Article.php.
When PHP needs the class, it automatically includes the matching file.
This example uses str_starts_with(), available in PHP 8.0 and later.
What Is PSR-4 Autoloading?
PSR-4 is a widely used PHP standard that defines how namespaces and class names map to file locations.
For example, consider this mapping:
| Namespace Prefix | Base Directory |
|---|---|
App/ |
src/ |
Under this mapping:
| Class Name | File Location |
|---|---|
App/Content/Article |
src/Content/Article.php |
App/Services/Mailer |
src/Services/Mailer.php |
PSR-4 makes class locations predictable and allows libraries and applications to follow the same autoloading conventions.
The namespace prefix and directory mapping must be configured. PHP doesn't automatically apply PSR-4 without an autoloader.
Using Composer for Autoloading
Composer is PHP's dependency manager. It also provides a convenient autoloader that supports PSR-4.
In modern PHP projects, Composer autoloading is generally preferable to maintaining a custom autoloader.
Assuming Composer is installed, let's configure it for the same project.
Step 1: Create composer.json
In the project root, create a file named composer.json:
{
"autoload": {
"psr-4": {
"App//": "src/"
}
}
}
This tells Composer to associate the App/ namespace prefix with the src directory.
Step 2: Generate the Autoloader
Open a terminal in your project directory and run:
composer dump-autoload
Composer generates the necessary autoload files inside a vendor directory.
If you're setting up a project that also has dependencies, composer install installs those dependencies and generates the autoloader.
Step 3: Load Composer's Autoloader
Replace the contents of index.php with:
<?php
declare(strict_types=1);
require __DIR__ . "/vendor/autoload.php";
use App/Content/Article;
$article = new Article("Learning PHP Autoloading");
echo htmlspecialchars(
$article->getTitle(),
ENT_QUOTES,
"UTF-8"
);
Output:
Learning PHP Autoloading
Composer now handles loading the Article class automatically.
Run the example from the project directory using:
php index.php
You no longer need a custom autoload function or a separate require statement for each class.
Common Autoloading Mistakes
| Problem | Solution |
|---|---|
| Class not found | Check the namespace, class name, file location, and autoload configuration. |
| Incorrect capitalization | Match class names and file paths exactly, especially on case-sensitive filesystems. |
| Missing vendor/autoload.php | Run composer install or composer dump-autoload, as appropriate. |
| New namespace mapping doesn't work | Update composer.json and regenerate Composer's autoload files. |
| Assuming use loads files | Remember that use imports a name; autoloading loads the class definition. |
Also remember that standard PSR-4 autoloading is designed for class-like definitions, including classes, interfaces, traits, and enums. It doesn't automatically load ordinary standalone functions.
When Should You Use Autoloading?
For a small script containing only one or two files, manually including files may be sufficient.
For applications with multiple classes, autoloading provides a cleaner structure and reduces repetitive code.
Composer is particularly useful when working with third-party packages, frameworks, or applications expected to grow over time.
Key Takeaways
- Autoloading loads PHP classes when they're needed.
- Use
spl_autoload_register()to register a custom autoloader. - PSR-4 maps namespace prefixes to directories.
- Composer provides a ready-made PSR-4 autoloader.
- Use
composer dump-autoloadafter changing autoload mappings. - Include
vendor/autoload.phpto enable Composer autoloading. - Namespaces organize class names, while autoloaders locate their definitions.
PHP autoloading helps keep projects organized as they grow. Understanding how autoloaders work is useful, but for most modern applications, Composer and PSR-4 provide a straightforward, maintainable solution.