PHP Defining Multiple Namespaces in same file

PHPServer Side ProgrammingProgramming

Introduction

More than one namespaces can be defined in a single file with .php extension. There are two diferent methods prescribed for the purpose. combination syntax and bracketed syntax

Multiple Namespaces with Combination Syntax

In this example two namespaces are defined one below the other. Resources in first namespace are available till second definition begins. If you want to make a namespace as current load it with use keyword.

Example

 Live Demo

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

Output

Above code shows following output

myspace1 : Hello World from space1
myspace2 : Hello World from space2
Hello World from space2
Hello World from space2

Multiple Namespaces with bracketed Syntax

In following example two namespaces are defined with their scope marked by curly brackets

Example

 Live Demo

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

Output

Above code shows following output

myspace1 : Hello World from space1
myspace2 : Hello World from space2

Bracketed syntax for multiple namespaces is recommended over combined syntax. Bracketed and unbracketed namespaces can not be mixed. Except for an opening declare statement, no other PHP code may exist outside of the namespace brackets. If you have to combone global namespace with named namespace, only bracketed syntax is allowed.

raja
Published on 18-Sep-2020 12:59:16
Advertisements