Namespaces are one of the most significant changes in PHP 5.3. They will be familiar to C# and Java developers, and they are likely to change the structure of PHP applications for the better.
Why Do We Need Namespaces?
As the size of your PHP code library increases, there is increased risk of accidentally re-defining a function or class name that has been declared before. The problem is exacerbated when you attempt to add third-party components or plugins; what if two or more code sets implement a ‘Database’ or ‘User’ class?
Until now, the only solution has been long class/function names. For example, WordPress prefixes every name with ‘WP_’. The Zend Framework uses a highly descriptive naming convention that results in long-winded class names such as Zend_Search_Lucene_Analysis_Analyzer_Common_Text_CaseInsensitive.
Name collision problems can be solved with namespaces. PHP constants, classes, and functions can be grouped into namespaced libraries.
How are Namespaces Defined?
By default, all constant, class, and function names are placed in the global space — like they were before PHP supported namespaces.
Namespaced code is defined using a single namespace keyword at the top of your PHP file. It must be the first command (with the exception of declare) and no non-PHP code, HTML, or white-space can precede the command, e.g.
<?php
// define this code in the 'MyProject' namespace
namespace MyProject;
// ... code ...
The code following this line will be assigned to the ‘MyProject’ namespace. It is not possible to nest namespaces or define more than one namespace for the same code block (only the last will be recognized). However, you can define different namespaced code in the same file, e.g.
<?php
namespace MyProject1;
// PHP code for the MyProject1 namespace
namespace MyProject2;
// PHP code for the MyProject2 namespace
// Alternative syntax
namespace MyProject3 {
// PHP code for the MyProject3 namespace
}
?>
Although this is possible, I would advise against it: retain your sanity by defining a single namespace per file.
Sub-namespaces
PHP allows you to define a hierarchy of namespaces so libraries can be sub-divided. Sub-namespaces are separated using a backslash (\) character, e.g.
- MyProject\SubName
- MyProject\Database\MySQL
- CompanyName\MyProject\Library\Common\Widget1
Calling Namespaced Code
In a file named lib1.php, we will define a constant, a function, and a class within the App\Lib1 namespace:
lib1.php
<?php
// application library 1
namespace App\Lib1;
const MYCONST = 'App\Lib1\MYCONST';
function MyFunction() {
return __FUNCTION__;
}
class MyClass {
static function WhoAmI() {
return __METHOD__;
}
}
?>
We can now include this code in another PHP file, e.g.
myapp.php
<?php
header('Content-type: text/plain');
require_once('lib1.php');
echo \App\Lib1\MYCONST . "\n";
echo \App\Lib1\MyFunction() . "\n";
echo \App\Lib1\MyClass::WhoAmI() . "\n";
?>
No namespace is defined in myapp.php so the code exists in the global space. Any direct reference to MYCONST, MyFunction or MyClass will fail because they exist in the App\Lib1 namespace. To call code in lib1.php, we can add a prefix of \App\Lib1 to define fully-qualified names. The following result is output when we load myapp.php:
App\Lib1\MYCONST
App\Lib1\MyFunction
App\Lib1\MyClass::WhoAmI
Fully-qualified names can become quite long and there are few obvious benefits over defining long class names such as App-Lib1-MyClass. Therefore, in the next article, we will discuss aliasing and take a closer look at how PHP resolves namespace names.
See also:
- How to Use PHP Namespaces, Part 2: Importing, Aliases, and Name Resolution
- How to Use PHP Namespaces, Part 3: Keywords and Autoloading
- How to Install PHP 5.3 on Windows







[...] How to Use PHP Namespaces, Part 1: The Basics – [...]
July 13th, 2009 at 5:28 pm
[...] about plugins as of July 13, 2009 Monday, July 13th, 2009 How to Use PHP Namespaces, Part 1: The Basics – sitepoint.com 07/13/2009 Namespaces are one of the most significant changes in PHP 5.3. [...]
July 13th, 2009 at 6:00 pm
[...] How to Use PHP Namespaces, Part 1: The Basicssitepoint.com [...]
July 13th, 2009 at 6:40 pm
that’s the worst solution for namespacing a language I’ve ever seen. Why the hell couldn’t it be made like in java!
Reason I don’t like this solution is, that all this means even more typing in the Editor, IDE (if used). Especially if it doesn’t have any support for namespaces.
Imagine the amount of information you have to type into php files:
-> I have to address the php file with “namespace”
-> I have to include the file rather than just importing it (in both cases typing is needed, I know)
-> I have to use a full qualified namespace for each class or constant or static function I want to use
-cs-
July 13th, 2009 at 7:40 pm
@carestep, while this blog post doesn’t bring it up. There is the use construct which is importing. Also with autoloading there is no need to include any of your classes/object.
July 13th, 2009 at 8:27 pm
@carstep:
1: Are you wining about the fact that you need to type “namespace foo;” at the beginning of each file? If so, Java required you to have “package foo;”, remember?
2: Including / requiring files has been the PHP since the beginning. Thats just how it works. It would be rather redundant to create a new way of importing code, just for the sake of namespaces. It would also be confusing.
3: You’ve forgotten the words ” if I’m using them in a different namespace then where they where defined and am to lazy to call ‘use Namespace\Foo\Bar\Whatever’.” (Note that ‘use’ isn’t covered in this article. Thats probally why its subtitled “The Basics”, and why they promis to handle resolving namespaces in the next article.)
And lastly, PHP != Java.
July 13th, 2009 at 9:27 pm
[...] http://www.sitepoint.com/blogs/2009/07/13/php-53-namespaces-basics/ [...]
July 13th, 2009 at 10:17 pm
@Jory Greets
I know well that PHP != Java. I apologize for comparing Java namespaces / package architecture to the PHP one, but typing as much in case of PHP is for me a bit overhauled “technique”. I was using Java only with well equipped IDE’s there comes my opinion that packaging in Java is more convenient. Yes my first reaction was shocking and misleading in this comparison but my reasons remained unchanged, explaining it below.
1. I remember. Even java could have used an autoloading mechanism alike (see point 2.)
2. Maybe. With a little more intelligent namespacing “technique” this could have been avoided, e.g. using automatized auto-loading mechanism for namespaces
3. No (in case of), conflicting classes can throw php error, to correct them using proper namespaces instead. Only in these cases should file including / namespace including mechanism used, regarding point 2.
My only goal was to highlight, how many repetitive action you have to do using namespaces.
Yes, Java is not perfect as well, I don’t use it much often.
-cs-
P.S.: sorry, English is not my native so fine tuning sentences is not my strongest skill :-)
July 13th, 2009 at 10:55 pm
@logic_earth
I missed you reply. Just realized it. Sure your reply points out some of my opinions as well.
To say the through autoloading and namespacing are similar techniques and could have been merged almost perfectly.
-cs-
July 13th, 2009 at 10:59 pm
When you are defining the name space in your library you get to do like:
namespace App\Lib1;It would be nice if you could also use something like this in your “myapp” example:
use namespace App\Lib1;Which would cause all the functions/objects, etc. to automatically have the namespace added.
Otherwise, namespaces provide little improvement over just using some obscure naming convention or prefixes.
July 14th, 2009 at 12:49 am
@Crowe, I don’t follow what you mean with “use namespace” if you define a namespace you can use every function, class, constant without using the namespace prefix. Also sub-namespace only needs first level below the current namespace.
For example for “App\Lib1″ if you have an object that needs to access an object in “App\Lib1\Sub” you only need “Sub\ObjectName” but any object in “App\Lib1″ can be access as “ObjectName”.
July 14th, 2009 at 2:00 am
Your post has invalid PHP syntax. You can’t combine bracketed namespaces and unbracketed namespaces in the same file.
July 14th, 2009 at 2:54 am
@carestep
Note that this is part 1 of a 3-part article. Tomorrow, we will cover the use statement and how PHP resolves namespace names. The next day, we look at autoloading namespaced code and a few advanced options.
PHP’s syntax is very similar to C#. Java uses non-hierarchical packages, but it’s the much the same concept.
July 14th, 2009 at 3:39 am
[...] use, it’s time to familiarize yourself with some of the new features that come with it. In this new tutorial from SitePoint they look at one of the more controversial additions – namespaces. Namespaces are [...]
July 14th, 2009 at 5:02 am
@Craig Buckler
okok, I wait for the next 2 parts engaged
-cs-
July 14th, 2009 at 6:04 am
Interesting article Craig.
I’m waiting for parts 2 & 3 as well but part 1 has me thinking.
Andrew
July 14th, 2009 at 7:14 am
Yet another reason it’s time to fork PHP.
July 14th, 2009 at 8:31 am
[...] use, it’s time to familiarize yourself with some of the new features that come with it. In this new tutorial from SitePoint they look at one of the more controversial additions – namespaces. [...]
July 14th, 2009 at 11:00 am
will the namespace usage by mandatory?
July 14th, 2009 at 2:23 pm
[...] PHP 5.3 Namespace Basics PHP craig buckler, PHP, zend [...]
July 14th, 2009 at 3:32 pm
Really thanks for the information.
July 14th, 2009 at 5:30 pm
[...] part 1, we discussed why PHP namespaces are useful and the namespace keyword. In this article, we examine [...]
July 14th, 2009 at 6:00 pm
@skunkbad
No, namespaces are not mandatory. Your non-namespaced code exists in a ‘global space’ — like it did before PHP 5.3.
If your application needs to support lower versions of PHP, then namespaces should be avoided for now. However, as we move on, I suspect many more applications will use namespaces. That can only be a good thing.
July 14th, 2009 at 6:08 pm
Part 2 is now available…
July 14th, 2009 at 6:09 pm
[...] part 1, we discussed why PHP namespaces are useful and the namespace keyword. In this article, we examine [...]
July 14th, 2009 at 7:25 pm
I think it’s time to move on to python.
July 14th, 2009 at 10:48 pm
Can one use “/” or “.” instead of “\” ?
July 14th, 2009 at 11:21 pm
[...] – How to Use PHP Namespaces part1 and part [...]
July 14th, 2009 at 11:35 pm
@lordspace
no, the backslash “\” is a non-configurable delimiter
July 15th, 2009 at 12:19 am
@lordspace
xqt is correct.
A double-colon (::) was originally proposed and implemented in betas. I’m not sure when and why it changed — but it was probably to stop any confusion with static methods. However, you will still find many articles that refer to double colons.
July 15th, 2009 at 1:03 am
[...] das novidades da versão 5.3) estes dois artigos devem interessar: How to use PHP Namespaces (parte 1 e parte 2). Li bem rápido a parte 1 e confesso que não chegarei até a parte 2. Eu gosto de PHP [...]
July 15th, 2009 at 7:18 am
How to Use PHP Namespaces, Part 1: The Basics…
PHP namespaces is a feature introduced in PHP 5.3. It’s something that exists in many programming languages helping php developers to structure their code in an improved manner and to avoid collisions between classes and functions with the same name. …
July 15th, 2009 at 8:21 am
[...] part 1, we discussed why PHP namespaces are useful and the namespace keyword. In this article, we examine [...]
July 15th, 2009 at 5:17 pm
[...] How to Use PHP Namespaces, Part 1: The Basics [...]
July 15th, 2009 at 5:20 pm
[...] parts 1 and 2 of this series, we looked at PHP namespace basics, the use operator, and name resolution. In this final article we discuss some of the more advanced [...]
July 15th, 2009 at 6:56 pm
xqt, Craig Buckler thank you for the info.
Yes I do remember that I’ve seen some code examples wih the double-colon (::).
July 15th, 2009 at 7:32 pm
[...] parts 1 and 2 of this series, we looked at PHP namespace basics, the use operator, and name resolution. In this final article we discuss some of the more advanced [...]
July 15th, 2009 at 7:33 pm
[...] How to Use PHP Namespaces, Part 1: The Basics How to Use PHP Namespaces, Part 2: Importing, Aliases, and Name Resolution How to Use PHP Namespaces, Part 3: Keywords and Autoloading VN:F [1.5.4_809]please wait…Rating: 0.0/10 (0 votes cast)VN:F [1.5.4_809]Rating: 0 (from 0 votes) Share and Enjoy: [...]
July 16th, 2009 at 4:05 pm
[...] How to Use PHP Namespaces, Part 1: The Basics [...]
July 16th, 2009 at 4:24 pm
[...] parts 1 and 2 of this series, we looked at PHP namespace basics, the use operator, and name resolution. In this final article we discuss some of the more advanced [...]
July 16th, 2009 at 4:47 pm
[...] Sitepoint wird uns der Umgang mit den neuen “Namespaces” in PHP 5.3 (Teil 1) erklärt. (Teil [...]
July 18th, 2009 at 3:49 pm
this is wonderful tutorial .. i read it 3 times and get a fantastic results and sure i put a
copy of this lesson on my site here
http://sahaebda3.zaghost.com/vb
July 18th, 2009 at 8:26 pm
[...] How to Use PHP Namespaces, Part 1: The BasicsFirst part of a tutorial about PHP Namespaces which are possible since latest stable release 5.3.0 [...]
July 20th, 2009 at 6:06 am
[...] su primera parte, hablan de cómo crear un namespace y de cómo utilizarlo después. Hablando de la existencia de [...]
July 20th, 2009 at 5:15 pm
[...] recomendada: espacios de nombres en PHP 5.3 En Sitepoint hay un buen artículo donde se explica la nueva funcionalidad incluida en PHP 5.3, los espacios de nombres. Lectura recomendada. Por : David « 5 razones por las [...]
July 25th, 2009 at 6:46 am
[...] How to Use PHP Namespaces, Part 1: The Basics: How to Use PHP Namespaces, Part 2: Importing, Aliases, and Name Resolution: How to Use PHP Namespaces, Part 3: Keywords and Autoloading: [...]
July 25th, 2009 at 6:28 pm
[...] Read this article: How to Use PHP Namespaces, Part 1: The Basics [...]
July 30th, 2009 at 5:16 pm
[...] rest is here: How to Use PHP Namespaces, Part 1: The Basics By: Admin Date: July 13, 2009 12:19 pm Categories: Blog, Blogs, Object, Wordpress, [...]
August 7th, 2009 at 9:24 pm
[...] recent tutorials received a number of comments complaining about namespace implementation in PHP. The main issues [...]
August 13th, 2009 at 2:52 am
[...] recent tutorials received a number of comments complaining about namespace implementation… [...]
August 13th, 2009 at 3:42 am
[...] Part 1: The Basics (0 visite) [...]
August 15th, 2009 at 5:56 pm
[...] Part 1: The Basics () [...]
August 15th, 2009 at 6:34 pm
[...] Tutorial en francais Articles en anglais [...]
August 17th, 2009 at 5:08 pm
[...] 10. How to Use PHP Namespaces [...]
August 21st, 2009 at 2:45 am
[...] How to Use PHP Namespaces, Part 1: The Basics (tags: tutorial development toread oop tutorials reference sitepoint programming php webdesign howto webdev) [...]
August 24th, 2009 at 12:33 am
[...] PHP开发者对于PHP中命名空间的实现,已经变得异常的渴望。当PHP应用开始变得巨大,并且更加复杂的时候,命名空间是解决代码冲突的必要手段。 我最近的一些指南收到了大量关于PHP的命名空间实现的评论。问题主要集中在语法和反斜杠上面。在解决这些问题之前,让我们先来快速回顾一下PHP的历史。 [...]
September 2nd, 2009 at 12:27 pm