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.
<?php
class Logger {}
class Logger {} // the same name again
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.
App\Billing\Logger <- one Logger
Vendor\Library\Logger <- another Logger
Both exist together, because the full names differ.
<?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();
}
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
- No collisions. Your
Userclass and a library’sUserclass can coexist. - Organisation. Names show where a class belongs:
App\Http\Controllers\UserControllersays 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.
<?php
namespace App\Models;
class User {}
echo User::class;
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_anddp_). 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).
Why this matters in WordPress and Laravel
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.