One of the most common issues is that spl_autoload_register wasn’t correctly invoked or got overwritten elsewhere. For example, if multiple autoloaders are registered in the wrong order, some classes might not be found.
<?php
spl_autoload_register(function ($class) {
include __DIR__ . '/classes/' . $class . '.php';
});
Ensure this anonymous function is registered and executed. You can use spl_autoload_functions() to check the list of currently registered autoload functions.
When using namespaces, class names include backslashes (\). If these aren’t correctly translated into directory separators, the file won't be found.
<?php
spl_autoload_register(function ($class) {
$path = __DIR__ . '/src/' . str_replace('\\', '/', $class) . '.php';
require $path;
});
Note: You must use str_replace('\\', '/', $class) to convert namespaces into directory paths.
On case-sensitive file systems (like Linux), the class name's case must exactly match the file name. If you develop on Windows (case-insensitive) and deploy to Linux, class not found errors can occur.
It's recommended to follow the PSR-4 naming convention and use Composer's autoloader to avoid such issues.
Another common reason is an incorrect path or root directory. For example, the following path concatenation may fail if the project structure changes:
require 'classes/' . $class . '.php';
A more robust approach is to use an absolute path:
require __DIR__ . '/classes/' . $class . '.php';
Or use realpath() to verify the path exists.
Even if the autoload logic is correct, the autoloader can't load a class if the target file doesn’t exist or wasn’t properly created. In this case, debugging with the following approach is helpful:
<?php
spl_autoload_register(function ($class) {
$file = __DIR__ . '/classes/' . $class . '.php';
if (!file_exists($file)) {
error_log("Autoload failed: $file not found");
}
require $file;
});
If you’re using Composer for autoloading (recommended), ensure the following:
composer dump-autoload has been run to ensure vendor/autoload.php is up to date.
require 'vendor/autoload.php'; is correctly invoked and the path is accurate.
<?php
require __DIR__ . '/vendor/autoload.php';
You can verify if the file is correctly deployed by visiting the project’s https://gitbox.net/vendor/autoload.php.