PHP Namespaces
As a project grows — and especially once you install libraries with Composer — name clashes become a real risk. Your code has a Logger class, a library has a Logger class, and a framework has yet another one. Namespaces solve this the same way folders solve duplicate file names: each class lives inside a named container, so App\Logger and Vendor\Logger can coexist.
Declaring a namespace
In real projects each file starts with a single namespace line, right after <?php:
<?php
namespace App\Models;
class User
{
// full name of this class: App\Models\User
}Namespace parts are separated by backslashes. By convention (PSR-4) they mirror the folder structure: App\Models\User lives in src/Models/User.php, and Composer's autoloader finds it automatically.
Several namespaces in one file
For the playgrounds below we need everything in a single file. PHP allows that with the braced syntax, where each block declares its namespace and code outside any named namespace goes into namespace { ... } (the global namespace):
<?php
namespace App\Models {
class User
{
public function __construct(public string $name) {}
}
}
namespace App\Services {
class User
{
public function describe(): string
{
return "I am the service, not the model";
}
}
}
namespace {
$model = new App\Models\User("Mai");
$service = new App\Services\User();
echo $model->name, "\n";
echo $service->describe(), "\n";
echo get_class($model), "\n";
echo App\Services\User::class, "\n";
}Mai
I am the service, not the model
App\Models\User
App\Services\User
Two classes named User live happily side by side, because their full names differ.
Qualified names
How PHP resolves a name depends on how you write it:
| Form | Example | Resolved as |
|---|---|---|
| Unqualified | User |
Current namespace + User |
| Qualified | Models\User |
Current namespace + Models\User |
| Fully qualified | \App\Models\User |
Exactly App\Models\User |
A leading backslash always means "start from the global root".
Importing with use
Typing long names everywhere is tedious. The use statement imports a name so you can refer to it by its short form, and as lets you pick an alias when two imports would clash:
<?php
namespace Shop\Billing {
class Invoice
{
public function __construct(public int $number) {}
}
}
namespace Shop\Shipping {
class Invoice
{
public function __construct(public string $carrier) {}
}
}
namespace App {
use Shop\Billing\Invoice;
use Shop\Shipping\Invoice as ShippingNote;
$bill = new Invoice(1042);
$note = new ShippingNote("DHL");
echo "Bill #", $bill->number, "\n";
echo "Shipped with ", $note->carrier, "\n";
echo __NAMESPACE__, "\n";
}Bill #1042
Shipped with DHL
App
The magic constant __NAMESPACE__ contains the current namespace name.
You can also import functions and constants:
use function App\Helpers\slugify;
use const App\Config\VERSION;
use App\Models\{User, Order, Product}; // group importFunctions, constants and the global fallback
Namespaces apply to functions and constants as well as classes. When you call an unqualified function or constant, PHP first looks in the current namespace and then falls back to the global one. That is why strlen() works inside any namespace. Classes do not fall back: inside a namespace, Exception means Current\Namespace\Exception unless you write \Exception or import it.
<?php
namespace Tools\Text {
function shout(string $s): string
{
return strtoupper($s) . "!";
}
const SEPARATOR = " | ";
function demo(): void
{
echo shout("hi"), SEPARATOR, strlen("namespace"), "\n";
try {
throw new \RuntimeException("needs a leading backslash");
} catch (\Exception $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}
}
}
namespace {
use function Tools\Text\shout;
Tools\Text\demo();
echo shout("imported"), "\n";
echo Tools\Text\SEPARATOR === " | " ? "constant ok" : "missing", "\n";
}HI! | 9
RuntimeException: needs a leading backslash
IMPORTED!
constant ok
Tip: In namespaced files, always write
\Exception,\DateTime,\PDOand other built-in classes with a leading backslash, or adduse Exception;at the top. Forgetting this is the most common namespace bug.
Namespaces and autoloading
In a Composer project you rarely write require for classes. Instead composer.json maps a namespace prefix to a folder:
{
"autoload": {
"psr-4": { "App\\": "src/" }
}
}After composer dump-autoload, writing new App\Models\User() makes the autoloader include src/Models/User.php on demand.
Note: Braced, multi-namespace files are perfectly valid PHP but unusual in real projects. The standard is one class per file with one
namespaceline at the top.
Test yourself
Which character separates parts of a PHP namespace?
./\::
Inside namespace App;, how do you refer to PHP's built-in Exception class reliably?
Exception\Exceptionoruse Exception;global\ExceptionApp\Exception
What does use Shop\Billing\Invoice as Bill; do?
- Creates a new class
Bill - Lets you write
Billto meanShop\Billing\Invoice - Copies the class into the current file
- Renames the class everywhere