PHP Namespaces

Organizing code and avoiding name conflicts

📦 What are PHP Namespaces?

Namespaces organize code into logical groups and prevent naming conflicts. They work like folders on your computer, allowing you to have classes with the same name in different namespaces without conflicts.


<?php
// Define a namespace
namespace MyApp\Models;

class User {
    public $name = "John";
}

// Use the class
$user = new User();
echo $user->name; // John
?>
                                    

Why Use Namespaces?

🚫

Avoid Conflicts

Prevent class name collisions

Unique Names Safe
📁

Organization

Group related code together

Structured Clean
📚

Better Code

Improve code readability

Maintainable Clear
🔌

Libraries

Essential for modern PHP packages

Composer PSR-4

🔹 Basic Namespace Declaration

Namespaces are declared at the beginning of a PHP file using the namespace keyword. They must be the first statement in the file, before any other code.

<?php
namespace App\Controllers;

class HomeController {
    public function index() {
        return "Welcome to Home Page";
    }
}

// Using the class in the same namespace
$controller = new HomeController();
echo $controller->index();
?>

Output:

Welcome to Home Page

🔹 Using Classes from Different Namespaces

To use a class from a different namespace, you can either use the fully qualified name or import it with the use keyword for cleaner code.

<?php
namespace App\Models;

class Product {
    public $name = "Laptop";
}

namespace App\Controllers;

// Method 1: Fully qualified name
$product1 = new \App\Models\Product();
echo $product1->name . "<br>";

// Method 2: Using 'use' statement
use App\Models\Product;

$product2 = new Product();
echo $product2->name;
?>

Output:

Laptop

Laptop

🔹 Sub-namespaces

Namespaces can be nested to create a hierarchical structure, similar to folders and subfolders, helping you organize complex applications more effectively.

<?php
namespace App\Database\Models;

class User {
    public $role = "admin";
}

namespace App\Database\Controllers;

class UserController {
    public function getUser() {
        // Access class from sibling namespace
        $user = new \App\Database\Models\User();
        return "User role: " . $user->role;
    }
}

$controller = new UserController();
echo $controller->getUser();
?>

Output:

User role: admin

🔹 The 'use' Keyword

The use keyword imports classes, functions, or constants from other namespaces, making your code cleaner and easier to read by avoiding long fully qualified names.

<?php
namespace App\Services;

class EmailService {
    public function send() {
        return "Email sent";
    }
}

class SmsService {
    public function send() {
        return "SMS sent";
    }
}

namespace App;

use App\Services\EmailService;
use App\Services\SmsService;

$email = new EmailService();
$sms = new SmsService();

echo $email->send() . "<br>";
echo $sms->send();
?>

Output:

Email sent

SMS sent

🔹 Aliasing with 'as'

When importing classes with the same name from different namespaces, use the as keyword to create aliases and avoid naming conflicts in your code.

<?php
namespace App\Models;

class User {
    public $type = "App User";
}

namespace Admin\Models;

class User {
    public $type = "Admin User";
}

namespace App;

use App\Models\User as AppUser;
use Admin\Models\User as AdminUser;

$appUser = new AppUser();
$adminUser = new AdminUser();

echo $appUser->type . "<br>";
echo $adminUser->type;
?>

Output:

App User

Admin User

🔹 Global Namespace

Classes without a namespace declaration belong to the global namespace. Use a backslash prefix to access global classes from within a namespace.

<?php
// Global namespace
class GlobalClass {
    public $name = "I'm global";
}

namespace App;

class LocalClass {
    public $name = "I'm local";
}

// Access global class with backslash
$global = new \GlobalClass();
$local = new LocalClass();

echo $global->name . "<br>";
echo $local->name;
?>

Output:

I'm global

I'm local

🔹 Namespace Constants and Functions

Namespaces can contain not only classes but also functions and constants, allowing you to organize all types of code elements logically.

<?php
namespace App\Helpers;

const APP_VERSION = "1.0.0";

function formatDate($date) {
    return date("Y-m-d", strtotime($date));
}

namespace App;

use function App\Helpers\formatDate;
use const App\Helpers\APP_VERSION;

echo "Version: " . APP_VERSION . "<br>";
echo "Date: " . formatDate("2025-10-14");
?>

Output:

Version: 1.0.0

Date: 2025-10-14

🔹 Practical Example: MVC Structure

Namespaces are essential in modern PHP applications, especially when following the MVC pattern. They help organize controllers, models, and views into logical groups.

<?php
namespace App\Models;

class Article {
    public $title = "PHP Namespaces";
}

namespace App\Controllers;

use App\Models\Article;

class ArticleController {
    public function show() {
        $article = new Article();
        return "Showing: " . $article->title;
    }
}

namespace App\Views;

use App\Controllers\ArticleController;

class ArticleView {
    public function render() {
        $controller = new ArticleController();
        return $controller->show();
    }
}

$view = new ArticleView();
echo $view->render();
?>

Output:

Showing: PHP Namespaces

🔹 Namespace Best Practices

✅ Do:

  • Use namespaces in all modern PHP projects
  • Follow PSR-4 autoloading standards
  • Match namespace structure to folder structure
  • Use meaningful namespace names
  • Import classes with use for readability
  • Use aliases when dealing with name conflicts

❌ Don't:

  • Mix multiple namespaces in one file
  • Use overly deep namespace hierarchies
  • Forget the leading backslash for global classes
  • Use generic names like "App" for libraries

🔹 Autoloading with Namespaces

Namespaces work perfectly with autoloading, allowing PHP to automatically load class files when needed. This is the foundation of modern PHP development with Composer.

<?php
// composer.json autoload configuration
{
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

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

class User {
    public $name = "Auto-loaded User";
}

// File: index.php
require 'vendor/autoload.php';

use App\Models\User;

$user = new User();
echo $user->name;
?>

Output:

Auto-loaded User

💡 Key Points to Remember:

  • Namespaces prevent naming conflicts
  • Declared with namespace keyword at file start
  • Use backslash (\) as namespace separator
  • Import classes with use keyword
  • Create aliases with as keyword
  • Access global classes with leading backslash
  • Can contain classes, functions, and constants
  • Essential for modern PHP and Composer packages

🧠 Test Your Knowledge

What character is used as the namespace separator in PHP?