PHP Defining Multiple Namespaces in same file

In PHP, you can define multiple namespaces within a single file using two different syntaxes: combination syntax (sequential) and bracketed syntax (enclosed). Each method has its own use cases and rules.

Multiple Namespaces with Combination Syntax

In combination syntax, namespaces are defined sequentially − one after another. The first namespace remains active until the second namespace declaration begins.

Example

<?php
namespace myspace1;
function hello() {
    echo "Hello World from space1<br>";
}
echo "myspace1 : ";
hello();

namespace myspace\space2;
function hello(){
    echo "Hello World from space2<br>";
}
echo "myspace2 : ";
hello();

// Using fully qualified names to call functions
echo "\nCalling with fully qualified names:<br>";
\myspace1\hello();
\myspace\space2\hello();
?>
myspace1 : Hello World from space1
myspace2 : Hello World from space2

Calling with fully qualified names:
Hello World from space1
Hello World from space2

Multiple Namespaces with Bracketed Syntax

The bracketed syntax uses curly braces to define the scope of each namespace explicitly. This approach is more organized and recommended for multiple namespaces.

Example

<?php
namespace myspace1 {
    function hello() {
        echo "Hello World from space1<br>";
    }
    echo "myspace1 : ";
    hello();
}

namespace myspace\space2 {
    function hello(){
        echo "Hello World from space2<br>";
    }
    echo "myspace2 : ";
    hello();
}
?>
myspace1 : Hello World from space1
myspace2 : Hello World from space2

Key Points

  • Bracketed syntax is recommended over combination syntax for multiple namespaces
  • You cannot mix bracketed and unbracketed namespace syntaxes in the same file
  • No PHP code can exist outside namespace brackets (except declare statements)
  • To combine global namespace with named namespaces, only bracketed syntax is allowed

Conclusion

Use bracketed syntax for better code organization when defining multiple namespaces in a single file. It provides clearer scope boundaries and is the recommended approach by PHP standards.

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

776 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements