PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 5 ■ OBJECT TOOLS


}


}


}


namespace main {
\com\getinstance\util\Debug::helloWorld();
}


If you must combine multiple namespaces in the same file, then this is the recommended practice.
Usually, however, it’s considered best practice to define namespaces on a per-file basis.
One feature that the braces syntax offers is the ability to switch to global space within a file. Earlier
on I used require_once to acquire code from global space. In fact, I could have just used the alternative
namespace syntax and kept everything on file.


namespace {
class Lister {
//...
}
}


namespace com\getinstance\util {
class Lister {
//...
}


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


I step into global space by opening a namespace block without specifying a name.

■Note You can’t use both the brace and line namespace syntaxes in the same file. You must choose one and


stick to it throughout.


Using the File System to Simulate Packages


Whichever version of PHP you use, you should organize classes using the file system, which affords a
kind of package structure. For example, you might create util and business directories and include class
files with the require_once() statement, like this:


require_once('business/Customer.php');
require_once('util/WebTools.php');


You could also use include_once() with the same effect. The only difference between the include()
and require() statements lies in their handling of errors. A file invoked using require() will bring down
your entire process when you meet an error. The same error encountered via a call to include() will
merely generate a warning and end execution of the included file, leaving the calling code to continue.
This makes require() and require_once() the safe choice for including library files and include() and
include_once() useful for operations like templating.

Free download pdf