Namespaces organize PHP code and prevent naming conflicts between classes from different libraries. Use namespace at the top of the file and import classes with use. Essential when building large apps with Composer packages.
Namespaces
// Declare namespace (must be first line)
namespace App\Models;
class User {
public string $name;
}
// ─────────────────────────────
namespace App\Controllers;
use App\Models\User;
use App\Services\AuthService as Auth;
class UserController {
public function __construct(private Auth $auth) {}
public function show(int $id): void {
$user = new User();
// ...
}
}
// ─────────────────────────────
// Global namespace
namespace {
$user = new \App\Models\User();
}