PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 5 ■ OBJECT TOOLS


that this is unlikely. After all, all you have to do is remember to give all your classes unique names, right?
The trouble is, we all rely increasingly on library code. This is a good thing, of course, because it
promotes code reuse. But what if your project does this:


// my.php


require_once "useful/Outputter1.php"
class Outputter {
// output data
}


and the included file does this:

// useful/Outputter1.php
class Outputter {
//
}


Well you can guess, right? This happens:

Fatal error: Cannot redeclare class Outputter in ../useful/Outputter1.php on line 3


Of course, as you’ll see there was a conventional workaround to this. The answer was to prepend
package names to class names, so that class names are guaranteed unique.


// my.php


require_once "useful/Outputter2.php";
class my_Outputter {
// output data
}


// useful/Outputter2.php


class useful_Outputter {
//
}


The problem here was that as projects got more involved, class names grew longer and longer. It
was not an enormous problem, but it resulted in issues with code readability, and made it harder to hold
classnames in your head while you worked. Many cumulative coding hours were lost to typos.
We’ll all be stuck with this convention for years to come, because most of us will be maintaining
legacy code in one form or other for a long time. For that reason, I’ll return to the old way of handling
packages later in this chapter.


Namespaces to the Rescue


Namespaces have been a wish-list feature for a long time now. The previous edition of this book
included a proposed implementation that made it into the PHP 6 development code. The developer
mailing lists have been lit up periodically by debates about the merits of the feature.
With PHP 5.3 the debates are academic. Namespaces are part of the language, and they’re here to
stay.

Free download pdf