3 Ways to Access a Namespaced PHP Class
Note: This article was originally published at Planet PHP on 29 November 2010.
Take this example (in a file called namespaced-class.php)
Now we have a few ways to access that class.
Refer Namespace and Class Name
The simplest way to access a class inside a namespace is simply to prefix the classname with its namespace(s):
$bird1 = new Christmas\DaysOf\PartridgeInAPearTree();
You can use this anywhere in your code.
Import the Namespace
In PHP we can import namespaces using the use keyword, and then just use the last part of the name in place of the namespace. In my contrived Christmas-related example, we'd end up with something that looks like this:
$bird2 = new DaysOf\PartridgeInAPearTree();
This example works well because it saves us from typing anything but the last element of a potentially quite long-winded path.
Alias the Namespace and/or Class
We can alias just the namespace, as shown above, or right down to the class name, using the use keyword. Optionally we can also rename what we'd like to call it, rather than the final element in the path, by using the as keyword.
use Christmas\DaysOf\PartridgeInAPearTree as Bird;A A A A A A
$bird3 = new Bird();
Even better, we can give a "nickname" to our namespace, either to avoid clashes or just to give us something more memorable or descriptive to use within the class. This will also be a great trick to use when namespace-using applications become legacy and we have to handle renaming of namespaces.
So Many Options
All of the above examples give a debug output of the same class; the class that was declared in the opening example file and included elsewhere. One thing I noted which was unfamiliar is that you must declare a namespace as the first thing in a file, and that the namespace is implicitly ended at the end of the file.
Are you using namespaces in your applications? How have you implemented them? I'm interested to hear how others are applying these techniques inside their architectures, please share!