You should really start namespacing your PHP

Namespaces have been usable since PHP 5.3, that’s a whole two and a bit years in which your code could’ve been a whole lot neater.

In this article I’ll show you the basics you need to know to make use of namespaces.

Namespacing is a way of separating whole projects and sections of projects in such a way as they cannot interfere with one another. Your first port of call for understanding namespaces should be the online manual.

Defining a namespace

The most basic namespace definition looks like this:

<?php

namespace Your\Namespace;

When you define your namespace, you should always place it before any other code in the file, and before anything is output. You should also add documentation:

<?php

/**
 * A description for your namespace.
 *
 * @package your-software-package
 */
namespace Your\Namespace;

You can also define multiple namespaces in a single file, although I would discourage from doing this unless absolutely necessary:

<?php

namespace Your\Namespace\A { ... }

namespace Your\Namespace\B { ... }

Using a namespace

The simplest way to use a namespace is to declare whatever code you’re working on as belonging to it:

<?php

namespace Other;

new Foobar();

This would let you create an instance of the Foobar class from the Other namespace. This is all fine, but what if you’re already working in a namespace? Well… then you must use another namespace, this is called importing:

<?php

namespace Your\Namespace;
use Other\Foobar;

new Foobar();

However, what if your namespace already has a Foobar class? Well… then you can import and alias:

<?php

namespace Your\Namespace;
use Other\Foobar as Boofar;

class Foobar extends Boofar { ... }

new Foobar();

Accessing the global namespace

PHP has what it calls a “global” namespace, this contains all of the standard PHP classes and extension classes that existed before namespaces where supported. Due to this, you have to do a little extra legwork to access the global namespace from within your own namespaces.

The following code would throw a fatal error (class not found):

<?php

namespace Your\Namespace;

$doc = new DOMDocument();

However you can use the global namespace from within your code either directly:

<?php

namespace Your\Namespace;

$doc = new \\DOMDocument();

Or by (and this is the smart option) aliasing the classes you need:

<?php

namespace Your\Namespace;
use DOMDocument;

$doc = new DOMDocument();

Doing this makes the code somewhat self documenting as it creates a section at the top of the document explaining exactly what classes and or functions are being used and from where.

In closing

While that’s all of the basics about namespaces out of the way, I still plan on covering some advanced uses and some nasty ways to abuse the concept in a later article. Stay tuned.

Share your thoughts...