0
0
PHPprogramming~5 mins

Sub-namespaces in PHP

Choose your learning style9 modes available
Introduction

Sub-namespaces help organize code into smaller groups inside bigger groups. This keeps code neat and avoids name clashes.

When you have many classes or functions and want to group them by feature or module.
When different parts of your project use the same class or function names.
When you want to make your code easier to find and maintain.
When working in a team and need clear code structure.
When building large applications with many components.
Syntax
PHP
<?php
namespace MainNamespace\SubNamespace;

class MyClass {
    // class code here
}
Use backslashes (\) to separate namespaces.
Sub-namespaces are like folders inside folders for your code.
Examples
This defines a class inside the App\Controllers sub-namespace.
PHP
<?php
namespace App\Controllers;

class HomeController {
    // code
}
This shows a function inside a deeper sub-namespace App\Models\User.
PHP
<?php
namespace App\Models\User;

function getUser() {
    // code
}
Here, Feature is inside a three-level sub-namespace.
PHP
<?php
namespace Company\Project\Module;

class Feature {
    // code
}
Sample Program

This program defines a Book class inside the Library\Books sub-namespace. It creates an object and prints the book title.

PHP
<?php
namespace Library\Books;

class Book {
    public function getTitle() {
        return "Learning PHP";
    }
}

// Using the class
$book = new Book();
echo $book->getTitle();
OutputSuccess
Important Notes

Remember to use the full namespace path when using classes from sub-namespaces outside their namespace.

You can use the use keyword to import sub-namespaces for easier access.

Summary

Sub-namespaces organize code into smaller groups inside bigger groups.

They help avoid name conflicts and keep code clean.

Use backslashes (\) to separate namespace levels.