PHP namespace keyword and __NAMESPACE__ constant


Introduction

In PHP, namespace keyword is used to define a namespace. It is also used as an operator to request access to certain element in current namespace. The __NAMESPACE__ constant returns name of current namespace

__NAMESPACE Constant

From a named namespace, __NAMESPACE__ returns its name, for global and un-named namespace it returns empty striing

Example

 Live Demo

#test1.php
<?php
echo "name of global namespace : " . __NAMESPACE__ . "
"; ?>

Output

An empty string is returned

name of global namespace :

For named namespace, its name is returned

Example

 Live Demo

<?php
namespace myspace;
echo "name of current namespace : " . __NAMESPACE__ . "
"; ?>

Output

name of current namespace : myspace

Dynamic name construction

__NAMESPACE__ is useful for constructing name dynamically

Example

 Live Demo

<?php
namespace MyProject;
class myclass {
   function hello(){echo "hello world";}
};
$cls="myclass";
function get($cls){
   $a = __NAMESPACE__ . '\' . $cls;
   return new $a;
}
get($cls)->hello();
?>

Output

Above code shows following output

hello World

namespace operator

The namespace keyword can be used as equivalent of the self operator for classes to explicitly request an element from the current namespace or a sub-namespace.

Example

 Live Demo

<?php
namespace Myspace;
class myclass {
   function hello(){echo "hello Myspace";}
}
$a = new namespace\myclass();
$a->hello();
?>

Output

Above code shows following output

hello Myspace

From global namespace, namespace operator refers to function/class in current namespace which is global namespace

Example

 Live Demo

<?php
class myclass {
   function hello(){echo "hello global space";}
}
$a = new namespace\myclass();
$a->hello();
?>

Output

Above code shows following output

hello global space

Updated on: 18-Sep-2020

316 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements