Namespaces — introduced in PHP V5.3 — are a way of giving your PHP classes, constants, and functions context so that elements with the same names can be understood as being unique. The unique names allow you to avoid naming collisions, which occur when two classes or functions of the same name exist. Sometimes, those PHP classes represent the same objects in your physical domain, but the behavior of the class is entirely different. Namespaces are a way of making sure you have the correct PHP class, constant, or function and that people using your PHP classes can be sure they're using the correct ones.
Namespaces in code work just like contexts in the physical world. Consider
a class that represents the real-world domain object automobile. To a
company that sells automobiles over the Internet, the
Automobile class may have entirely different behaviors
from the Automobile class a company that sells
insurance uses.
As an application developer, you might use components written by other
people. You can never be sure that those people didn't decide to use the
same class names you have, but for an entirely different class. Before
namespaces, it was typical for a PHP developer to build the context into
the name of the class, like
My_Enterprise_Person or
XML_Validator.
Listing 1 shows an example of a class that resides in a namespace.
Listing 1. Declaring a class in a namespace
<?php
namespace IBM;
class Foo {
...
}
?>
|
An example of referring to a class in a namespace is shown below.
Listing 2. Referring to a class in a namespace
<?php $foo = new \IBM\Foo(); ?> |
Defining a namespace policy is a good idea before you start adding namespaces to all your classes. Although it is acceptable to a certain extent to grow your namespaces by building them over time, it is better to decide a common structure for your namespaces that makes it easier to organize them and reduce the chance of a lot of rework later. When used correctly, namespaces can be a method for organizing your PHP code in addition to providing context.
Other languages, like the Java™ and C# languages, have had namespaces for a long time. In choosing how to name my namespaces, I use conventions similar to those languages because they're familiar and understood by many developers. However, unlike the Java language, the namespaces in PHP are not linked to the directory in which the class resides. You can give a class, function, or constant any namespace you choose. You can even use more than one namespace per file. And unlike C#, you can give namespaces to functions or constants that aren't inside classes.
If you are building applications for an organization, use your organization name as a high-level domain. Creating a high-level namespace with your organization name is usually enough to give your PHP code context and avoid naming collisions, unless your organization writes many applications for different purposes or for subdivisions.
Listing 3 contains an example of declaring a high-level namespace.
Listing 3. A high-level namespace
<?php namespace IBM; ... ?> |
Subnamespaces are namespaces inside high-level namespaces. They provide further clarification if the high-level namespace isn't enough to establish context for the PHP class you're creating.
When creating subnamespaces, it's important not to become overzealous and create too many. They become difficult to organize and reference later if they become too numerous. This is particularly important when you're using namespaces for the purpose of organizing your PHP code, as well as avoiding naming collisions.
When deciding how many subnamespaces to introduce into another namespace for organizational purposes, I try to keep the number limited to seven (plus or minus two) in order to take advantage of the idea that, conceptually, chunks of seven items are easier to remember. This doesn't always work, but I use it as a guideline to determine whether I'm carving up namespaces into too many subnamespaces.
Listing 4 shows an example of declaring a subnamespace inside a high-level namespace.
Listing 4. A subnamespace
<?php namespace IBM\DeveloperWorks; ... ?> |
The subnamespace ("DeveloperWorks") is separated from the high-level
namespace ("IBM") that contains it with the backslash
(\) character.
When you're declaring subnamespaces, you can use a couple of common techniques or a combination thereof. One common place to get names for subnamespaces is from project or application names; the other is from the domain name.
If you've used your organization name as the high-level namespace and still
seek subnamespaces to further provide context, you can use project or
application names as the name of a subnamespace. For instance, if you are
building a new application called Greeter that asks for users'
names and greets them, use a namespace like the one in Listing 5 to give
full context to a class called Prompt.
Listing 5. Using the application name as a subnamespace
<?php
namespace IBM\Greeter;
class Prompt {
...
}
?>
|
Because Prompt could be the name of a class in
several applications or libraries, providing this namespace with
the organization name and project name sets this
Prompt apart from the others.
Using the name of a domain is another common scheme for choosing subnamespace names, as Listing 6 shows. It may or may not be used in addition to the project name, depending on your plans for reusability (see "Naming for reusability").
A domain is a group or classification of things found in the larger problem domain. An example of a domain can be "Account," "Customers," or "Products" in a larger application that deals with accounts, customers, and products.
Listing 6. Using the domain as a subnamespace
<?php
namespace IBM\MyApp\Account;
class Address {
...
}
?>
|
In addition to applying concepts of modularity that enable reusability, the way you name classes and namespaces gives them an implied purpose and, therefore, reusability. Sometimes, poor naming choices hinder reusability because the poor names imply that a class is limited to a specific purpose. Similarly, namespaces when applied incorrectly can "specialize" classes unnecessarily and make them awkward to reuse elsewhere.
It can be important in a high-level namespace that carries an organization name to reserve a "Common," "Core," "Lib," or other namespace that can be used to store classes that can be reused across applications. Common examples are validation, where the rules for an enterprise-wide stock-keeping unit (SKU), account number, or invoice number are the same for proper format and length. For such a validator class, a good namespace may be something like Listing 7.
Listing 7. Using a common validation namespace
<?php
namespace MyCompany\Common\Validation;
class NotNullValidator {
...
}
?>
|
Here, the organization name is used as the high-level domain ("MyCompany"). The "Common" namespace is used as the project. Although this class was written perhaps while a specific application was written, the class can be used by any project in the organization. Finally, "Validation" is used as the domain for the class.
Although namespaces help you organize classes and avoid naming conventions, they do have the downside of longer names. Fortunately, PHP provides the ability to use an alias so that you can refer to the shorter alias name in your code. Listing 8 provides an example.
Listing 8. Using an alias
<?php use MyCompany\Common\Validation as Validators; ?> |
It is consistent with other PHP conventions — such as the PHP Extension and Application Repository (PEAR) package naming and file names — to use uppercase camel or PASCAL naming conventions with namespace names. For instance, prefer the namespace in Listing 9 over that in Listing 10.
Listing 9. Uppercase camel or PASCAL naming
<?php namespace MyNamespace; ?> |
Avoid using naming and case conventions that are contrary to the rest of the PHP conventions.
Listing 10. Using a poor convention for case
<?php namespace mynamespace; ... ?> |
Namespaces in PHP are a way to organize your code, avoid naming collisions, and provide context for your classes, functions, and constants. Using a scheme or convention for your namespaces allows your code to be easily understood, as well as easily referenced and used.
Learn
- Read about namespaces in the
PHP manual.
- Learn more about other
naming conventions
at Zend.com.
- Read
"What's new
in PHP V5.3"
to learn more about other new features in PHP V5.
-
PHP.net is the central resource for PHP
developers.
- Check out the
"Recommended PHP reading list."
- Browse all the
PHP content
on developerWorks.
- Follow
developerWorks on Twitter.
- Expand your PHP skills by checking out
IBM developerWorks'
PHP project resources.
- To listen to interesting interviews and
discussions for software developers, check out
developerWorks podcasts.
- Using a database with PHP? Check out the
Zend Core for
IBM,
a seamless, out-of-the-box, easy-to-install PHP development and production
environment that supports IBM DB2 V9.
- Stay current with developerWorks'
Technical events and webcasts.
- Check out upcoming conferences, trade
shows, webcasts, and other
Events
around the world that are of interest to IBM open source
developers.
- Visit the developerWorks
Open source zone
for extensive how-to information, tools, and project updates to help you
develop with open source technologies and use them with IBM's
products.
- Watch and learn about IBM and open source
technologies and product functions with the no-cost
developerWorks On demand demos.
Get products and technologies
- Innovate your
next open source development project with
IBM trial software,
available for download or on DVD.
- Download
IBM product evaluation versions
or
explore
the online trials in the IBM SOA Sandbox
and get your hands on application development tools and middleware
products from DB2®, Lotus®, Rational®, Tivoli®,
and WebSphere®.
Discuss
- Participate in
developerWorks blogs
and get involved in the developerWorks community.
- Participate in the developerWorks
PHP Forum: Developing PHP applications with IBM Information Management products (DB2, IDS).

Nathan A. Good lives in the Twin Cities area of Minnesota. Professionally, he does software development, software architecture, and systems administration. When he's not writing software, he enjoys building PCs and servers, reading about and working with new technologies, and trying to get his friends to make the move to open source software. He's written and co-written many books and articles, including Professional Red Hat Enterprise Linux 3, Regular Expression Recipes: A Problem-Solution Approach and Foundations of PEAR: Rapid PHP Development.




