PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 5 ■ OBJECT TOOLS


PHP Fatal error: Class 'main\com\getinstance\util\Debug' not found in .../listing5.04.php o
n line 12


That’s because I’m using a relative namespace here. PHP is looking below the namespace main for
com\getinstance\util and not finding it. Just as you can make absolute URLs and filepaths by starting
off with a separator so you can with namespaces. This version of the example fixes the previous error:


namespace main;


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


That leading backslash tells PHP to begin its search at the root, and not from the current
namespace.
But aren’t namespaces supposed to help you cut down on typing? The Debug class declaration is
shorter, certainly, but those calls are just as wordy as they would have been with the old naming
convention. You can get round this with the use keyword. This allows you to alias other namespaces
within the current namespace. Here’s an example:


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


The com\getinstance\util namespace is imported and implicitly aliased to util. Notice that I didn’t
begin with a leading backslash character. The argument to use is searched from global space and not
from the current namespace. If I don’t want to reference a namespace at all, I can import the Debug class
itself:


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


But what would happen if I already had a Debug class in the main namespace? I think you can guess.
Here’s the code and some output.


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


Debug::helloWorld();


PHP Fatal error: Cannot declare class main\Debug because the name is already in use in .../
listing5.08.php on line 13


So I seem to have come full circle, arriving back at class name collisions. Luckily there’s an answer
for this problem. I can make my alias explicit:


namespace main;

Free download pdf