Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
