Skip to main content

PHP Namespace

Word namespace is very contextual in the computer science. In the operating system, it has a different meaning, in the computer programming, it has a different meaning. But the final moto of the namespace is almost same and it is an organization of your things. In the computer programming, it means to organize your code. In this tutorial, we will learn what is the namespace, its basics and how to use in PHP. So in the complete tutorial if we will talk about namespace then it will have a direct relation to computer programming. Also, we will go too in-depth of PHP namespace feature, convention, and its uses.

What is Namespace

In Computer programming name is a feature to segregate your code to prevent the clashes in the name of your variables, constants, procedural methods, and classes. Namespace in the computer programming is same as directory bifurcation in the file system where the file with the same can exists but in two separate directories for folders.

With a large number of audience, it is a misconception that namespace is only part of object oriented programming where it can be used for classes, but this is not true. You can use namespace in procedural programming as well. You can use namespace in the procedural programming to club your code to prevent from clashes.

Where namespace can be used

Since the namespace add a level of separation for your codebase below are some good scenario where you can use namespaces.

  1.  Suppose you are working with a large team on a very large project and obviously you will be working on one thing at a time. Now you have to create a class for user, probably you can name it class User. And some time later or at the same moment, another developer also wants to create a class with name user and load on the same request. If another user will do this, PHP will always throw an error for the redeclaration of class. Hence in this case, if both will create a class with the namespace then conflict will never arise.
  2. Another use case is creation of opensource package. Now suppose you are creating a library and you do not who is going to use and where. Then it is always advisable to use the namespace.  Because your classes, methods or constants will may be conflicted with the user of the package. Hence if you will use namespace then definitely it will minimize chances of errors.

The Benefits

Till now I have explained that the naming conflict can be cater by namespaces. But it has several other benefits also. For example:

  1. Structuring of the code in a better way by grouping classes and methods of the same purpose in one group.
  2. Better reusability of the code.
  3. Resolving naming conflicts

Till now we have discussed lots of theory. Now it is time for action. From here onward we will explore the PHP namespace.

How to define a PHP Namespace

You can define a namespace in your php code by using namespace keyword. If you want to define the namespace then it should be the first thing of your code except declare a function. Means your namespace definition must have the first code of your php file except for the declare function. For example:
<?php
namespace Test;
function abc(){}
class test{}
$a = 5;
define('APPLE','YES');
?>

If you can see the above code then you can found that the first thing of our code is a namespace. If you will add some other code(except declare()) like below then it will throw a Fatal error in PHP.
<?php
$a = 'apple';
namespace Test;
function abc(){}
class test{}
$a = 5;
define('APPLE','YES');
?>

You can have any valid PHP code under your namespace. But the code which will be affected is a normal class, abstract class, traits, interface, functions, and constants. Which means one you will use the interface then the group bifurcation happens only for classes, traits, interfaces, functions and constants.

I will explain in the later part of the tutorial that how only all types of classes, interface, functions and constants will get affected.

Defining PHP Sub-Namespaces

You can take PHP namespaces to further deep down level and define subnamespace. A subnamespace can be declared using backslash with your main namespace.
<?php
namespace TestProject\UserModule;
define('USER_TYPE' , 1);
trait comman_methods{}
abstract class type{}
interface user_feature{}
class user{}
?>

As you can see in the above code I have declared a sub-namespace with name UserModule in namespace TestProject.
Now you can take it one more level in the namespace like below:
<?php
namespace TestProject\UserModule\Profile;
trait user_details{}
abstract class user_attributs{}
interface user_charecters{}
class user_profile{}
?>

Defining Multiple PHP Namespaces in a Single File

You can define multiple namespace in a single PHP File like below:
<?php
namespace NS1;
const X=2;
class nstest1{}
class nstext2{}
function nstestmethod(){}
namespace NS2;
const Y=2;
class ns2test1{}
class ns2test2{}
?>

Also you can use the bracket syntext like below:
<?php
namespace NS1{
const X=2;
class nstest1{}
class nstext2{}
function nstestmethod(){}
}
namespace NS2{
const Y=2;
class ns2test1{}
class ns2test2{}
}
?>

In this case no code should exists outside of namespace otherwise PHP will throw the fetal error. For example below code will always throw an error:
<?php
namespace NS{
const X=1;
}
$a = 123;
?>
So in such type of situation you can put your global code in unnamed namespace like below:
<?php
namespace NS{
const X=1;
}
namespace {
$a = 123;
}
?>

As the coding practice it is strongly discourage to create multiple namespace in single file. It is always better to create new file for your new namespace.

Using Namespaces in PHP

In previous sections, we have seen how to create a namespace, subnamespace, and namespace in single file. Let us see how to use the namespace in your code.Classes, methods, constants of namespaces can be accessed same as you access your files from the directory in a hierarchy. Same as file access in php namespaces also you can use relative or absolute path. For example:

file1.php(just a simple namespace):
<?php
namespace User\Profile;
const USER_TYPE='normal';
class User_Data{
private $user_id;
private $user_name;
public function __construct($id , $name) {
$this->user_id = $id;
$this->user_name = $name;
}
public function get_user(){
return array('id'=>$this->user_id,'name'=> $this->user_name);
}
}

file2.php(using namespace):
<?php
require_once './file1.php';
$usr = new User\Profile\User_Data(1, 'Ankur');
var_dump($usr->get_user());
var_dump(User\Profile\USER_TYPE);
?>

So if you want to use the namespace into another file just include the file and use the namespace in the same hierarchy in which it is defined. For example to access the class I have used User\Profile\User_Data or for the constat I have used User\Profile\USER_TYPE.

Similar to the directory system, if you are within the namespace you do not need to provide the path. Now let us take the same file1.php which we have used previously and see if we will use the class method in the same namespace:
<?php
namespace User\Profile;
const USER_TYPE='normal';
class User_Data{
private $user_id;
private $user_name;
public function __construct($id , $name) {
$this->user_id = $id;
$this->user_name = $name;
}
public function get_user(){
return array('id'=>$this->user_id,'name'=> $this->user_name);
}
}
var_dump(USER_TYPE);
$usr = new User_Data('1','Ankur');
var_dump($usr->get_user());
?>

No complete Path of the namespace is given because we are in the same namespace, we can simply use the Class name or constant.

Again like in directory system namespace work in a relative manner as well. If you are in a directory c:\xampp\htdocs and want to access any file of location c:\xampp\htdocs\techflirt\code\file.php then you can simply use vi techflirt\code\file.php. The same way namespace works. You can access your namespace relatively as well like Below:

file2.php:
<?php
namespace User\Profile\EditProfile;
class User_Form{
private $user_data;
public function __construct(User\Profile\User_Data $udata) {
$this->user_data = $udata;
}
public function get_profile_edit_form(){
print 'edit form will be generated';
}
}
?>

Now in file1.php we can put relative path as we are one namespace up in the hierarchay:

<?php
namespace User\Profile;
include './file2.php';
const USER_TYPE='normal';
class User_Data{
private $user_id;
private $user_name;
public function __construct($id , $name) {
$this->user_id = $id;
$this->user_name = $name;
}
public function get_user(){
return array('id'=>$this->user_id,'name'=> $this->user_name);
}
}
$usr = new User_Data('1','Ankur');
$edit_pro = new EditProfile\User_Form($usr);
$edit_pro->get_profile_edit_form()
?>

You can see here that we have not give full path of namespace EditProfile because we are one directory up in the namespace hierarchay.

Global VS Local in PHP Namespaces

The Beauty of the PHP namespace is preventing you from the collision with others code and sometimes with PHP global code as well.

For Example, you want to write your custom function for strpos but in your implementation sometime you want to use your custom strpos and sometime you want to use php strpos. So using namespace you can do. For accessing inbuilt PHP function you can use global namespace which is \. Below is the example:

<?php
namespace Test;
function strpos($mainstring, $search_string){
/*You custom logic of strpos*/
}
print strpos('mainstry','a');//this will call your local strpos
print \strpos('abc', 'b');//this will call php inbuilt strpos
?>

Import PHP Namespaces Using USE Keyword

You can import a namespace in PHP using keyword use. Let us again take an example of User Profile:
file1.php:
<?php
namespace User\Profile;
const USER_TYPE='normal';
class User_Data{
private $user_id;
private $user_name;
public function __construct($id , $name) {
$this->user_id = $id;
$this->user_name = $name;
}
public function get_user(){
return array('id'=>$this->user_id,'name'=> $this->user_name);
}
}
?>

Now we will import User_Data class like below in file2.php:
<?php
use User\Profile\User_Data;
include 'file1.php';
$usr = new User_Data('1', 'Ankur');
var_dump($usr->get_user());
?>

Hence in above code we have imported User_Data class in the beginning of the file with line use User\Profile\User_Data;

If you want to import the complete Namespace from file1.php then the code should be like below:
<?php
use User\Profile;
include 'file1.php';
$usr = new Profile\User_Data('1', 'Ankur');
var_dump($usr->get_user());
var_dump(Profile\USER_TYPE);
?>

In the above code we have imported complete User\Profile namespace using code use User\Profile. But since everything is imported we can also use constant like Profile\USER_TYPE.

Importing and Aliasing in PHP Namespace

While importing the PHP namespace you can also put an alias in the use statement and use your alias name where you have imported the namespace.

We will use the same file1.php where we can create a namespace User\Profile and create class user_data. Now we can alias the namespace with name usr_pro using “as” keyword.

<?php
use User\Profile as usr_pro;
include 'file1.php';
$usr = new usr_pro\User_Data('1', 'Ankur');
var_dump($usr->get_user());
var_dump(usr_pro\USER_TYPE);
?>

Simillarly you can import class:
<?php
use User\Profile\User_Data as udata;
include 'file1.php';
$usr = new udata('1', 'Ankur');
var_dump($usr->get_user());
?>

You can also alias constants for specific method fro php version 5.6 onwards like below:
<?php
use const User\Profile\USER_TYPE as UTYPE;
include 'file1.php';
var_dump(UTYPE);
?>

Magic Constant __NAMESPACE__

PHP provides __NAMESPACE Magic Constant. __NAMESPACE__ contains name of the namespace. Since it is a magic constant which value differes from situaltion to situation. Let us explore how magic constant behave.

If you will print __NAMESPACE__ in global namespace then it will return black. But if you will print __NAMESPACE__ in any of your own namespace then it will print name of your namespace. For example:
<?php
namespace Test\TestProject;
function abc(){
var_dump(__NAMESPACE__);//Print Test\TestProject
}
abc();
var_dump(__NAMESPACE__);//Print Test\TestProject
?>

Autoloading Of Namespace

If you want to autoload a namespace and the namespace has class then it is very easy. You can use php magic function __autoload and you will receive a complete name of the class along with your namespace name. And if you have created your namespace exactly as per your directly then it would be very very easy. For example:

I have a namespace with name Techflirt\Ns\Autoload\Test and it has 2 classes with name calculator and memory. The file name of the namespace is test.php and the test.php is in my xampp folder directory techflirt/ns/autoload. Let us call the memory class and use __autoload function to load the namespace.

test.php at location techflirt/ns/autoload which has classes:

<?php
namespace Techflirt\Ns\Autoload\Test;
const TEST = 1;
class calculator{
public function __construct() {
;
}
public function get_calculator(){
print 'Now you are getting your calculator';
}
}
class monitor{
public function __construct() {
;
}
public function get_monitor(){
print 'Now you are getting monitor';
}
}
?>

Now you can use __autoload function to load the namespace file like below:
<?php
use Techflirt\Ns\Autoload\Test;
function __autoload($class){
//replace \ with /
$class= str_replace("\\", DIRECTORY_SEPARATOR, strtolower($class));
require_once $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.dirname($class).'.php';
}
$calc = new Test\calculator();
?>

Above code is just for demonstration purpose. You can write it in much better manner.

Support Me by Sharing This Article

Ankur Kumar Singh

I am a PHP programmer having some knowledge about Linux. I am always interested in web development and knowledge sharing. I am full time tech evangelist part time human being. :-)

Leave a comment/Ask Question

shares