Sharing technology, ideas, insights!
Call: +91 710 466 0336         Email: hello@sanisoft.com

Blog

Namespaces in PHP 5.3 – Part 1

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:

  1. You need to have PHP 5.3 at least. Nopes, there’s no way it will work on 5.2.x versions.
  2. A namespace is defined using a “namespace” keyword. As you will see in the example coming up.
  3. 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.
  4. 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.
  5. Although it is possible, having multiple namespaces in a single file is not recommended.
  6. 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

Now say you define another greet() function inside another namespace say “GoodbyeWorld” in a file say ‘bye.php’

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 :


Interestingly  the delimiter ‘\’ was decided after a lot of hot debates and one of the proposals even included  : ) i.e the smiley :).  Although ‘::’ was proposed in some early phases, ‘\’ (backslash) is the only delimiter you can use with namespaces and this is not configurable by any means.

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

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

and using the same parent namespace we define a network.php

say if the above files were to be included in another you would need the following code to access

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.

const

About the Author

Jatin has been working with PHP for the last 7 years and is a Zend Certified PHP 5 Engineer.

4 comments

  1. Pingback: Tweets that mention Namespaces in PHP 5.3 – Part 1 at SANIsoft – PHP for E Biz -- Topsy.com

  2. Pingback: Namespaces in PHP 5.3 – Part 2 at SANIsoft – PHP for E Biz

  3. Pingback: Lambda functions and Closures in PHP 5.3 at SANIsoft – PHP for E Biz

Leave a Reply