PHP Declaring sub-namespaces

PHP allows creating nested namespaces, similar to how directories contain subdirectories in a file system. Sub-namespaces are declared using the backslash character \ to define the hierarchical relationship between parent and child namespaces.

Syntax

To declare a sub-namespace, use the following syntax ?

namespace ParentNamespace\ChildNamespace;

Example

Here's how to create and use sub-namespaces with functions ?

<?php
namespace myspace\space1;
function hello() {
    echo "Hello World from space1
"; } namespace myspace\space2; function hello(){ echo "Hello World from space2
"; } // Using fully qualified names myspace\space1\hello(); myspace\space2\hello(); ?>
Hello World from space1
Hello World from space2

Using the 'use' Keyword

You can import sub-namespaces with the use keyword for cleaner code ?

<?php
namespace myspace\space1;
function greet() {
    echo "Greetings from space1
"; } namespace myspace\space2; function greet() { echo "Greetings from space2
"; } use myspace\space1 as s1; use myspace\space2 as s2; s1\greet(); s2\greet(); ?>
Greetings from space1
Greetings from space2

Multiple Levels

Sub-namespaces can be nested to multiple levels ?

<?php
namespace company\department\team;
function work() {
    echo "Working in team namespace
"; } namespace company\department\management; function manage() { echo "Managing from management namespace
"; } company\department\team\work(); company\department\management\manage(); ?>
Working in team namespace
Managing from management namespace

Conclusion

Sub-namespaces provide hierarchical organization for PHP code, using backslashes to separate levels. Use fully qualified names or the use keyword with aliases for cleaner access to nested namespace elements.

Updated on: 2026-03-15T09:12:45+05:30

350 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements