devnotes.

Understanding Namespaces

Namespaces prevent naming collisions between classes, functions, and constants — essential once a project uses multiple libraries that might define classes with the same name (e.g. two different Request classes).

// File: app/Models/User.php
namespace App\Models;

class User
{
    public function __construct(public string $name) {}
}
// File: app/Services/UserService.php
namespace App\Services;

use App\Models\User; // import the class from another namespace

class UserService
{
    public function create(string $name): User
    {
        return new User($name);
    }
}

You can also alias an imported class to avoid a collision: use App\Models\User as UserModel;. Reference a fully-qualified class name from anywhere with a leading backslash: \App\Models\User.

Namespaces map naturally to directory structure by convention (though PHP doesn't strictly enforce this — Composer's autoloader is what actually connects the two, as covered on the next page). This is why App\Models\User typically lives at app/Models/User.php.

PHP Namespaces Explained | DevNotes