PHP Declaring sub-namespaces

PHPServer Side ProgrammingProgramming

Introduction

It is possible to create namespaces inside a namespace. Just as a directory in file system can contain sub directories in a heriarchical structure, sub-namespaces can be arranged in hierarchy. The backslash character \ is used to define the relationship between top level and sub-level namespace,

In this example toplevel namespace myspace contains two sub-namespaces space1 and space2. In order to access functions/classes inside a subnamespace, first make it available by use keyword

Example

 Live Demo

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

Output

Above code shows following output

Hello World from space2
Hello World from space2
raja
Published on 18-Sep-2020 09:35:24
Advertisements