Namespaces were created as part of PHP 5.3 to solve certain conflicts that can arise when two different classes are given the same name. This situation comes up more commonly than you might think. This four-part series introduces you to using namespaces to solve these and similar issues. It includes copious code examples to enhance your understanding.
If you’re an experienced PHP developer, then you’ll surely know that building web applications using the object-oriented paradigm can be a pretty challenging process, at least in the beginning. However, as you master the key concepts that surround the use of this approach, working with classes and objects becomes so familiar that you can start quickly developing more complex PHP programs.
While the learning process looks very educational and even fun, the truth is that things can get more complicated when you begin using third-party classes or even entire development frameworks. For instance, say that you’ve created a neat database abstraction class, called “MySQL,” which handles all of your database-related tasks.
So far, this class isn’t conflictive, right? But, this scenario may change for the worse if you decide to use a forum application created by another programmer, which also includes a class named “MySQL.” Whenever you try to use the forum’s classes and yours together, it’s possible that the PHP interpreter will complain loudly when it finds that you’re attempting to use two classes that share the same name!
Of course, you can solve this problem by renaming one of the conflictive classes, but sometimes this process can be a true nightmare, or simply a nonviable solution. Nonetheless, not all is lost in this case, because with the release of PHP 5.3, this problem could be easily solved by way of namespaces.
In simple terms, by using this feature it’s possible to specify that one or more PHP classes must belong to a certain namespace, which should avoid a naming conflict between classes like the one described above. In this particular case, you might specify that your MySQL class is valid within a namespace called “general,” while the forum’s class would be available in a “forum” namespace.
Understanding how namespaces work in PHP 5 naturally requires much more than simple theory. Therefore, in this group of articles, I’ll be developing for you several code samples, which hopefully will help you learn how to use this helpful feature within your forthcoming PHP applications.
Now it’s time to move past the preliminaries and start digging deeper into the use of namespaces in PHP 5. Let’s begin this educational journey now!