How to: Namespace in PHP

Namespacing has been long awaited to enhance PHP OO development, and it looks like it's finally here. At first, I thought it was going to become available in PHP6, but it has been ported to PHP 5.3.

What is a Namespace?

Namespacing provides you the freedom to name your classes what you want without worrying about any other classes, native to PHP or otherwise, interfering with your names.

Let's say for some crazy reason you wanted to create your own Soap Client. Well SoapClient is already a class within PHP so you would have to name your class something else. But what else would you name SoapClient than SoapClient? Thanks to namespacing, we don't have to worry about that anymore.

Here's a quick example:

  1. <?php
  2. namespace Coder1;
  3. class SoapClient
  4. {
  5. // ... class code here
  6. }
  7.  
  8. // create your new Coder1 Soap Client
  9. $sc = new Coder1::SoapClient();
  10.  
  11. ?>

There's not many classes in PHP we have to worry about, but there very well may be collisions when using libraries or frameworks.

Namespaces in PHP are not here without quirks. There is no encasing structure to a namespace declaration, so it applies to the entire file. Because of this, you can not nest or have more than one namespace per file.

Check out README.namespaces for the official documentation.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <img> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <h3> <h4> <h5> <h6> <h7>
  • Lines and paragraphs break automatically.
  • Images can be added to this post.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.