Namespaces in PHP are used to group classes, functions, and constants under a unique name to avoid name conflicts. They allow you to organize code in a modular and maintainable way, especially in large applications. Namespaces are declared using the namespace
keyword at the top of a PHP file. They are useful when combining multiple libraries or creating reusable components. You can access namespaced elements using the use
statement or fully qualified names.
1. Declare a Namespaced Class
<?php
namespace App\Controllers;
class HomeController {
public function index() {
echo "Welcome to HomeController";
}
}
File Name: HomeController.php
2. Use a Namespaced Class with use
<?php
require 'App/Controllers/HomeController.php';
use App\Controllers\HomeController;
$controller = new HomeController();
$controller->index();
File Name: index.php
or any main script like test.php
3. Use Without use
Keyword
<?php
require 'App/Controllers/HomeController.php';
$controller = new \App\Controllers\HomeController();
$controller->index();
File Name: index.php
(or main.php
, etc.)
4. Use Alias with as
<?php
require 'App/Controllers/HomeController.php';
use App\Controllers\HomeController as Home;
$home = new Home();
$home->index();
File Name: index.php
or alias-test.php
Full Example Folder Structure:
project-root/
│
├── index.php ← Calls the controller
│
└── App/
└── Controllers/
└── HomeController.php ← Namespaced class
Summary Table
Code Type | File Name | Folder Path |
---|---|---|
Declare namespace/class | HomeController.php |
/App/Controllers/ |
Use namespaced class (with use ) |
index.php |
Project root |
Use class with \Namespace\ |
index.php |
Project root |
Alias namespace using as |
index.php |
Project root |