PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 5 ■ OBJECT TOOLS

So, what are they? In essence a namespace is a bucket in which you can place your classes, functions
and variables. Within a namespace you can access these items without qualification. From outside, you
must either import the namespace, or reference it, in order to access the items it contains.
Confused? An example should help. Here I rewrite the previous example using namespaces:


namespace my;
require_once "useful/Outputter3.php";


class Outputter {
// output data
}


// useful/Outputter3.php
namespace useful;


class Outputter {
//
}


Notice the namespace keyword. As you might expect that establishes a namespace. If you are using
this feature, then the namespace declaration must be the first statement in its file. I have created two
namespaces: my and useful. Typically, though, you’ll want to have deeper namespaces. You’ll start with
an organization or project identifier. Then you’ll want to further qualify this by package. PHP lets you
declare nested namespaces. To do this you simply use a backslash character to divide each level.


namespace com\getinstance\util;


class Debug {
static function helloWorld() {
print "hello from Debug\n";
}
}


If I were to provide a code repository, I might use one of my domains: getinstance.com. I might then
use this domain name as my namespace. This is a trick that Java developers typically use for their
package names. They invert domain names so that they run from the most generic to the most specific.
Once I’ve identified my repository, I might go on to define packages. In this case I use util.
So how would I call the method? In fact it depends where you’re doing the calling from. If you are
calling the method from within the namespace, you can go ahead and call the method directly:


Debug::helloWorld();


This is known as an unqualified name. Because I’m already in the com\getinstance\util
namespace, I don’t have to prepend any kind of path to the class name. If I were accessing the class from
outside of a namespaced context I could do this:


com\getinstance\util\Debug::helloWorld();


What output would I get from the following code?

namespace main;


com\getinstance\util\Debug::helloWorld();


That’s a trick question. In fact this is my output:
Free download pdf