As soon as a project has more than a handful of classes — or uses any external package (covered in the Composer lesson ahead) — two classes with the same name is a real risk. A namespace prevents that collision.
A namespace declaration must be the very first statement in a PHP file.
<?php
namespace App\Models;
class User {
// this class's full name is App\Models\User
}<?php
namespace App\Models;
class User { /* ... */ }
namespace App\Auth;
class User { /* ... */ } // a completely different class,
// fully named App\Auth\User —
// no naming conflict at all<?php
namespace App\Controllers;
use App\Models\User;
$user = new User(); // resolves to App\Models\UserUseful when two classes from different namespaces would otherwise share the same short name.
use App\Models\User;
use App\Legacy\User as LegacyUser;
$user = new User();
$oldUser = new LegacyUser();Namespaces usually mirror folders
The convention followed by nearly every modern PHP project — and the one Composer's autoloading (next lesson) expects — is one namespace matching the folder structure: App\Models\User lives in app/Models/User.php.