PHP error guide

PHP "Class not found": Autoloading, Namespaces and Composer Fixes

Error summary

PHP could not load the class—usually a Composer PSR-4 mismatch, missing `vendor/autoload.php`, wrong namespace/case, or a class file that was never installed.

What it means

PHP could not load the class—usually a Composer PSR-4 mismatch, missing vendor/autoload.php, wrong namespace/case, or a class file that was never installed.

What the error means

The autoloader (or manual include) did not define the requested class before it was referenced.

Why PHP produces it

PHP resolves classes at runtime through registered autoloaders. If Composer mappings or file paths do not match the fully-qualified class name (including case on Linux), resolution fails.

PHP version notes

Message may appear as Error: Class "X" not found on PHP 7+.

Most common causes

  • Forgot require vendor/autoload.php
  • PSR-4 namespace/path mismatch in composer.json
  • Case-sensitive filesystem path mismatch
  • Missing composer dump-autoload after moving classes
  • Package not installed / wrong dependency version

Minimal examples

BAD — reproduces the problem

php
// missing vendor/autoload.php\n$mailer = new App\\Service\\Mailer();

FIXED — safer pattern

php
require __DIR__ . '/../vendor/autoload.php';\n$mailer = new App\\Service\\Mailer();

Step-by-step diagnosis

  1. Confirm the exact FQCN in the error.
  2. Verify vendor/autoload.php is loaded in the front controller.
  3. Check composer.json autoload.psr-4 prefixes against the directory layout.
  4. Run composer dump-autoload -o and retry.

Fixes

Fix #1: Load Composer autoload

Require the generated autoloader once at bootstrap.

php
require __DIR__ . '/../vendor/autoload.php';\n\nuse App\\Service\\Mailer;\n$mailer = new Mailer();

Fix #2: Correct PSR-4 mapping

Align namespace prefixes with directories, then dump autoload.

json
{\n  \"autoload\": {\n    \"psr-4\": {\n      \"App\\\\\": \"src/\"\n    }\n  }\n}

Common mistakes when fixing it

  • Running composer install on a different machine than the web SAPI uses
  • Committing incomplete vendor/ without lockfile consistency

How to prevent it

  • CI job that boots the app and instantiates critical services
  • Use composer validate and optimized autoload in deploy

Web server / environment notes

Composer projects on Linux are case-sensitive—common CI-only failure

Tags: cli,fpm,composer,linux,docker

Categories

Relevant ZendStudio.net tools