Namespaces
On this page
Why Namespaces Exist
Namespaces prevent class/function name collisions and help organize large codebases. They are essential in modern PHP projects, especially with Composer autoloading.
Basic Namespace Example
Namespace declarations must be at the top of the file.
<?php
namespace App\Controllers;
class ItemController {
public function index(): void {
echo "Items";
}
}
Using a Namespaced Class
Use use statements to import classes. This keeps code readable.
<?php use App\Controllers\ItemController; $controller = new ItemController(); $controller->index();
Fully Qualified Names
You can always reference a class by its full name (starting with backslash).
<?php $controller = new \App\Controllers\ItemController();
Production Tip
Adopt a consistent namespace structure that matches your folder structure (PSR-4). This prepares your codebase for Composer and modern frameworks.