PHP Namespaces

PHP Namespaces

Namespaces organise code into logical groups and prevent naming collisions between your code and third-party libraries.

1 - Declaring

<?php
// File: src/Models/User.php
namespace App\Models;

class User {
    public function __construct(public readonly string $name) {}
}

2 - Using

<?php
// Full qualified name (no import needed)
$user = new \App\Models\User("Alice");

// With use statement
use App\Models\User;
$user = new User("Alice");

// Alias
use App\Models\User as UserModel;
$user = new UserModel("Alice");

3 - Grouped Use (PHP 7+)

use App\Models\{User, Post, Comment};
use App\Services\{Mailer, Notifier};

$user    = new User("Alice");
$mailer  = new Mailer();

4 - Functions and Constants

namespace App\Utils;

const VERSION = "1.0.0";

function formatDate(string $date): string {
    return date("d M Y", strtotime($date));
}

// Elsewhere:
use function App\Utils\formatDate;
use const App\Utils\VERSION;

echo formatDate("2024-05-01"); // 01 May 2024
echo VERSION;                  // 1.0.0

Note: The namespace declaration must be the very first statement in a file (only the opening PHP tag and declare() may precede it). Place it before any class or function definitions.

-Tip-