PHP namespaces

For those of you who are not following the PHP internals mailing list, the namespaces subject has been brought up again, with a simple implementation from Dmitry Stogov.

Its hard to say if it actually gets integrated in the source, as its a touchy subject and many implementations have came before this; but I love the way its implemented.

Quotes from Dmitry:

Namespaces are defined the following way:

namespace Zend::DB;

class Connection {

function connect() {

Namespace definition does the following:
All class and function names inside are automatically prefixed with namespace name. Inside namespace, local name always takes precedence over global name. It is possible to use the same namespace in several PHP files.
The namespace declaration statement must be the very first statement in file.

Every class and function from namespace can be referred to by the full name
- e.g. Zend::DB::Connection or Zend::DB::connect - at any time.

require 'Zend/Db/Connection.php';
$x = new Zend::DB::Connection;

Namespace or class name can be imported:

require 'Zend/Db/Connection.php';
import Zend::DB;
import Zend::DB::Connection as DbConnection;
$x = new Zend::DB::Connection();
$y = new DB::connection();
$z = new DbConnection();

Web mentions


  • nirn


  • pcdinh


    Because PHP support procedural programming technique so add a line namespace Zend::DB is very difficult to read and find out which scope namespace cover. E.x:

    namespace Zend::DB
    echo 'Hello there';

    class DoSomething {

    interface CanDoIt {


    foreach ($seats as $seat) {


    You can see many language constructs here that can be mixed and confused with namespace scope.

    Why can we offer a new keyword that can be used with extends or implements in class declaration. Ex: class A extends B in namespaceC...

    class A extends B in namespaceC {

  • Evert


    It's really a matter of taste.. I actually like the 'namespace' keyword.. 'package' would be even better I think..

    In any case, i don't really care how it works, as long as it works.. You can never really please everybody..

    If you structure your code well, and add proper docblocks everywhere there never really should be an issue.. Beginners will likely not use namespaces anyway, and if they are interacting with other people's libraries; they should be properly documented.