Skip to content

PHP Tutorial Namespaces and Autoloading

Why Namespaces Exist

Lesson 239 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Imagine two libraries that both define a class called Logger. PHP cannot have two classes with the same name. The second one causes a fatal error.

index.php
PHP
<?php
class Logger {}

class Logger {}   // the same name again
Output
OUTPUT
Fatal error: Cannot declare class Logger, because the name is already in use in /path/to/index.php on line 4

As projects pull in code from many places, name clashes become likely. Namespaces solve this.

The folder idea

On your computer, two files can both be called index.html as long as they are in different folders. A namespace is like a folder for names of classes, interfaces, functions and constants.

Text
PLAIN
App\Billing\Logger     <- one Logger
Vendor\Library\Logger  <- another Logger

Both exist together, because the full names differ.

index.php
PHP
<?php
namespace App\Billing {
    class Logger
    {
        public function name(): string { return "Billing logger"; }
    }
}

namespace Vendor\Library {
    class Logger
    {
        public function name(): string { return "Library logger"; }
    }
}

namespace {
    echo (new App\Billing\Logger())->name() . "\n";
    echo (new Vendor\Library\Logger())->name();
}
Output
OUTPUT
Billing logger
Library logger

(Normally each namespace lives in its own file, with a single namespace App\Billing; line at the top. The braces here are only to show several namespaces in one example.)

Two benefits

  1. No collisions. Your User class and a library’s User class can coexist.
  2. Organisation. Names show where a class belongs: App\Http\Controllers\UserController says a lot.

Fully qualified names

The full name of a class includes its namespace: App\Billing\Logger. In strings, you can also write it with a leading backslash: \App\Billing\Logger.

index.php
PHP
<?php
namespace App\Models;

class User {}

echo User::class;
Output
OUTPUT
App\Models\User

::class returns the fully qualified name as a string. It is the right way to get a class name in code.

Who uses namespaces

  • Composer packages put all their code in a vendor namespace (Monolog\Logger, Carbon\Carbon).
  • Laravel and Symfony projects use App\... for application code.
  • WordPress itself mostly avoids namespaces (it uses function prefixes such as wp_ and dp_). Modern WordPress plugins increasingly use them.

What namespaces are not

They are not about security or about folders on disk. They are just a naming mechanism. The link between a namespace and a folder is a convention, handled by autoloading (see Autoloading).

info
Why this matters in WordPress and Laravel
In Laravel every file starts with a namespace App\...; line. In WordPress, plugins without namespaces rely on long prefixes (myplugin_function_name) to avoid clashes. A namespace is the cleaner version of that habit.