In PHP, namespaces are used to avoid name conflicts between classes, functions, and constants. They allow you to organize code into logical groups. This is especially useful in large projects or when using third-party libraries that may define classes or functions with the same name.
Think of namespaces as folders in your file system — two files with the same name can exist in different folders without conflict. Similarly, two classes with the same name can exist in different namespaces.
use keyword.A namespace is declared using the namespace keyword at the top of a PHP file. Multiple namespaces can exist across different files, and classes can be imported using aliases for cleaner and more readable code.
// Defining model namespace
<?php
namespace App\Models {
class User {
public function __construct() {
echo "User model initialized<br>";
}
}
}
// Defining controller namespace
namespace App\Controllers {
class User {
public function __construct() {
echo "User controller initialized<br>";
}
}
}
// Global namespace usage with aliases
namespace {
use App\Models\User as ModelUser;
use App\Controllers\User as ControllerUser;
$model = new ModelUser();
$controller = new ControllerUser();
}
?>
The output shows that two different User classes can coexist peacefully. Each class belongs to its own namespace and is instantiated using an alias, ensuring there is no conflict.
Visualize namespaces like folders:
App
├── Models → User
└── Controllers → User
namespace at the top of your PHP file.