PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 5 ■ OBJECT TOOLS

use com\getinstance\util\Debug as uDebug;


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


uDebug::helloWorld();


By using the as clause to use, I am able to change the Debug alias to uDebug.

If you are writing code in a namespace and you want to access a class that resides in global (non-
namespaced) space, you can simply precede the name with a backslash. Here’s a method declared in
global space:


// global.php: no namespace


class Lister {
public static function helloWorld() {
print "hello from global\n";
}
}


And here’s some namespaced code that references the class:

namespace com\getinstance\util;
require_once 'global.php';
class Lister {
public static function helloWorld() {
print "hello from ".NAMESPACE."\n";
}
}


Lister::helloWorld(); // access local
\Lister::helloWorld(); // access global


The namespaced code declares its own Lister class. An unqualified name accesses the local version.
A name qualified with a single backslash will access a class in global space.
Here’s the output from the previous fragment.


hello from com\getinstance\util
hello from global


It’s worth showing, because it demonstrates the operation of the NAMESPACE constant. This will
output the current namespace, and is useful in debugging.
You can declare more than one namespace in the same file using the syntax you have already seen.
You can also use an alternative syntax that uses braces with the namespace keyword.


namespace com\getinstance\util {
class Debug {
static function helloWorld() {
print "hello from Debug\n";

Free download pdf