One of the most significant and welcome features added in PHP 5.3 was that of namespaces. While this has been around in other programming languages, namespaces have finally found their place starting with PHP 5.3. If you are not new to namespaces and have worked on them in other languages don’t go away, you might find a few interesting things. By the time you are done reading you’ll find out how this works with PHP. If you are completely new the namespaces this blog is for you and should help you get started with namespaces.
What are namespaces ?
A Namespace can be simply seen as logical container which is used to encapsulate or group related classes, functions or constants. Basically namespaces help your code to be uniquely identified and help avoid conflicts with other code. Say when you put your code can go under a namespace it would be unique from other’s code even if they have the same entity name as yours.
That’s Savvy. Why should I care ?
Why in the world add another headache and learn this new thing at all you say ? As you read on you will realize it actually saves you from a lot of headache later on. Lets consider the example of file-system directory. You cannot have 2 file names called “user.php” in the same directory can you ? But if you create two different directories say “admin” and “member” you can put those respective “user.php” files and they will live happily ever after.
Namespaces do the samething in the programming world. They help prevent conflicts. So you can have say the same classname “User” with different namespaces and you can use both without worrying about conflicts. Apart from this you can have your functions and classes named same as the internal PHP functions but used with a unique namespace. Also with namespaces you also get rid of the what I call “anaconda” class / function name syndrome
which has been a issue in libraries and frameworks for long.
For e.g take an example of this:
Zend_Search_Lucene_Analysis_Analyzer_Common_Text_CaseInsensitive class or function wp_dashboard_trigger_widget_control
With namespaces you can eliminate this extra long name and make it short and sweet.
If you are one of those who likes descriptive namespace names there something’s called ‘alias’ which lets you assign a short ‘alias’ for the anaconda namespace you chose. We will cover that in the next part .
Ok, I am impressed. Show me how.
Using namespaces is no rocket science. but there are a few things you must remember before you start using them:
- You need to have PHP 5.3 at least. Nopes, there’s no way it will work on 5.2.x versions.
- A namespace is defined using a “namespace” keyword. As you will see in the example coming up.
- Except the ‘declare’ keyword (mostly used for defining encoding of a source file), a file containing a namespace must declare the namespace at the top of the file before any other code. Of course except the comments and whitespace.
- As always you cannot use the reserved keywords. Say you can’t define a namespace and have a ‘echo’ function or class named Static or a constant with a name of a reserved keyword.
- Although it is possible, having multiple namespaces in a single file is not recommended.
- You cannot nest namespaces.
Ok, Enough. Show me the code!
What could be a better way than your favorite “Hello World” example
Consider this code snippets
Say you write a function greet(), now you define it in a file say ‘hello.php’ with a namespace ‘HelloWorld’ it would look like
- // Namespace for this class
- namespace HelloWorld;
- // Just a function that echos nothing fancy
- function greet()
- {
- echo "Hello World";
- }
Now say you define another greet() function inside another namespace say “GoodbyeWorld” in a file say ‘bye.php’
- // Namespace for this class
- namespace GoodbyeWorld;
- // Just a function that echos nothing fancy
- function greet()
- {
- echo "Good Bye World!";
- }
Now, You include these files in a file say a greet.php, you would now need to call the greet() function with the namespace you want like below :
- // Include the required files
- include('hello.php');
- include('bye.php');
- // Use the namespace with function call
- HelloWorld\greet();
- GoodbyeWorld\greet();
Interestingly the delimiter ‘\’ was decided after a lot of hot debates and one of the proposals even included : ) i.e the smiley
So now you can have a greet() number of times provided you use a unique namespace! ok, this example was for a function but you can use the same concept to encapsulate classes and constants too, as you will see in coming examples.
But if I define no namespace where in the world does it go ?
Say in the greet.php if you define a function greet() like below
- // Include the required files
- include('hello.php');
- include('bye.php');
- //a function defined without a namespace.
- function greet()
- {
- echo "Hello Global \n";
- }
- // this will call the function without a namespace.
- greet();
- // Calling functions from respective namespaces.
- HelloWorld\greet();
- GoodbyeWorld\greet();
It goes in the default namspace i.e the “Global” namespace. It would behave same as any code before namespaces were introduced.
So the first greet() function calls the greet function from the global namespace. If there were no greet() function in the global namespace you would be hit by a fatal error.
ok, thats kewl, but like sub directories can I have sub-namespaces.
Yes, Sub-namespaces are supported by PHP and help you create a hierarchy so as to suit your application.
Just like you need to have say folders “Company” and in that you can have “Accounts”, “Networking”, You may need a namesapace say something like the following code, also check how we can use a ‘const’ (again new in PHP 5.3) i.e a constant with namespaces :
say you put this in a account.php
- // Declare namespace
- namespace Company\Accounts;
- // Constant below is now in the above namespace
- const fileName = 'account.php';
- // A class in above name space
- class User {
- }
and using the same parent namespace we define a network.php
- // Declare namespace
- namespace Company\Networking;
- // Constant below is now in the above namespace
- const fileName = 'network.php';
- // A class in above name space
- class User {
- }
say if the above files were to be included in another you would need the following code to access
- // Include the required file
- include('account.php');
- include('network.php');
- // print out the constants based on the name spaces
- echo Company\Accounts\fileName;
- echo Company\Networking\fileName;
- // Create instance of User class from both the namespaces
- $accountUser = new Company\Accounts\User();
- $networkUser = new Company\Networking\User();
Note how we have this time used namespaces with classes and a constant.
By now, you must have had a fair enough idea about how to define and use namespaces in PHP.
Ok great, Is that all I need to know about namespaces ?
No, thats not all about namespaces in PHP. Here are some the topics that we will cover in the next edition.
- Assigning alias to avoid long namespaces.
- Importing namespaces using the ‘use’ keyword.
- Auto-loading namespaces.
Keep an eye on this post for the Part 2 ! and as usual update me with your thoughts and comments.

Thanks it was really awesome .
. Great work.
I hope this post will help every newbies to PHP 5.3