Namespaces are a way of grouping related classes, interfaces, functions, and constants. They solve a major problem in large PHP applications: **Name Collisions**. They allow you to have two classes with the same name as long as they are in different namespaces.
Imagine you are using two different external libraries. Both libraries have a class named User. Without namespaces, PHP wouldn't know which one you want to use, and your script would crash with a "Cannot redeclare class" error.
Namespaces are like **folders** on your computer. You can have two files named index.php as long as they are in different folders. Namespaces bring this same logic to your PHP code.
A namespace must be declared at the **very top** of a PHP file, before any other code (except for a possible declare statement).
<?php
namespace App\Models;
class User {
public function getName() {
return "John Doe";
}
}
?>
To use a class that is inside a namespace, you have three options:
Access the class by its full "path" every time you use it.
<?php
$user = new \App\Models\User();
?>
Import the namespace at the top of your file. This is the most common and recommended way.
<?php
use App\Models\User;
$user = new User(); // Now you can use the short name
?>
If you have two classes with the same name from different namespaces, you can give one of them an "alias".
<?php
use App\Models\User as LocalUser;
use ExternalLib\User as RemoteUser;
$user1 = new LocalUser();
$user2 = new RemoteUser();
?>
Namespaces are often structured to match your folder structure (following the PSR-4 standard). For example:
namespace App\Controllers; (Stored in /src/Controllers/)namespace App\Models; (Stored in /src/Models/)namespace App\Helpers; (Stored in /src/Helpers/)\) as a separator for namespaces, not a forward slash.
Exception or DateTime) by putting a backslash in front of them (e.g., new \Exception()) if you are inside a namespace.