PHP Namespaces for Beginners

Namespaces are a way to encapsulate item. Just think like your D:\songs directory in your Computer. You may have sub divided songs folder into multiple folders like D:\songs\pop, D:\songs\Hiphop, D:\songs\Rock, D:\songs\Jazz and D:\songs\Classical. In each sub folder there are hundreds of songs with different names. You can add attitude.mp4 in different directories like D:\songs\Jazz\attitude.mp3 or D:\songs\pop\attitude.mp4. But you can not add attiude.mp4 in a same directory twice right?

But if you can try this at your PC then one file name will attitude.mp4 and second file name will be copy attitude.mp4.

In PHP, Namespaces was introduced in 5.3 to solve conflict between code authors and ability to shorten (alias) long name to improve readability of source code.

You must define namespace at the top of the php file using namespace keyword like namespace MyCart;.


Defining Namespace: (mycart.php)

Calling Namespace: (order.php)

In the above code, I have included mycart.php and create a class object by calling new MyCart\ShoppingCart(). At this point you may notice 2 things one is MyCart after new and second is '\'. Please note that you have to add namespace before calling a class and '\' is used as a separator.

Calling Namespace: Using ‘Use’ Keyword (order.php)

In the above code, I include ShoppingCart using 'use' keyword and after that I create a object of ShoppingCart(). It is best for those who autoload their classes and this method is mostly used in php frameworks like Laravel.

Calling Namespace: Using Alias (order.php)

In the above code, I created Cart as an alias of MyCart\ShoppingCart and create a object using Cart(). This is the beauty of namespaces that you refer to an external fully qualified name with an alias.

Output:

Defining sub-namespaces: (mycart2.php)

Php namespaces also has the ability to work like a hierarchy. Like my first example of songs directory that have songs\pop folder inside it.

I am going to create another file in a same directory level as mycart2.php and will add below code there.

So you may notice that after namespace keyword I added Cart2\MyCart which will be working like parent and child directories. I also created another ShoppingCart class with order method.

Calling sub-namespaces: (order.php)

Output:

 

Posted in PHP

Author: Ahsan Zameer

I am a web developer and love to search new stuff on web. Trying different approaches and ideas to make web developing more interesting and enjoyable.