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:

<?phpnamespace Coder1;class SoapClient{  // ... class code here}// create your new Coder1 Soap Client$sc = new Coder1::SoapClient();?>

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.