PHP Declaring sub-namespaces


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


 Live Demo

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


Above code shows following output

Hello World from space2
Hello World from space2

Updated on: 18-Sep-2020


Kickstart Your Career

Get certified by completing the course

Get Started