PHP 6 Namespaces

Speaking of the future of PHP, the PHP internals team has been talking about implementing namespaces in PHP 6. The problem they want to solve is this: how do you keep two class names (such as “Connection”) from interfering with each other? On a small web site, it’s easy, but once a site becomes complex or you start adding in third-party plug-ins and re-using old code, it gets much harder. Currently developers are using very long class names to help ensure their uniqueness, and no one likes that solution much.

The leading proposal at the moment was put forward by Dmitry Stogov on the PHP-Dev list. His idea is to declare the namespace at the beginning of the file and then all function names would be prefixed with the namespace name.

I like the idea, I like the “::” seperators, but I don’t like being restricted to declaring it at the top of the file. Why not just envelope the namespace anywhere (using curly-braces)? Then you don’t have to be at the top of the file and you can put more than one namespace in a file. It seems much more flexible than a single declaration in a required position.

namespace Zend::DB {
  class Connection {...}
  function connect() {...}
}
namespace AltZend::DB {
  class Connection {...}
}

You could even go further and allow namespaces to be inside other name spaces.

namespace PP {
  namespace DB {
    class Connecton {...}
    function connect() {...}
  }
  class Foo {...}
  function bar() {...}
}
$x = new PP::DB::Connection;
PP::DB::connect();
$y = new PP::Foo;
PP::bar();

Ruby gives this namespace behavior using Modules.

What do you think? They are looking or feedback and ideas.

3 Responses to “PHP 6 Namespaces”

  1. Amaury Bouchard Says:

    Why not another possibility?

    For example something like :
    class AA::BB::CC {
    }
    class AA::BB::DD {
    }
    class AA::EE::CC {
    }

    $c1 = new AA::BB::CC();
    $c2 = new AA::EE::CC();

    Pretty simple, no ?

    It could work even for non-OOP:
    function AA::BB::func($param) {
    }
    const ZZ::YY::C = “foo”;

    AA::BB::func(ZZ::YY::C);

  2. Kevin Skoglund Says:

    Definitely another candidate to consider. I’m in support of any syntax that includes curly-braces to limit the start and end of the namespace.

    The one downside to your idea is that it requires rewriting “class” and I’m sure that’s a bigger project than they were hoping to take on to get namespaces implemented.

    Right now, Dmitry Stogov’s patch is still the leading one, but it’s not without controversy.

  3. Null is Love » Blog Archive » Namespaces Come to PHP Says:

    [...] in July, I wrote that the PHP internals team was discussing implementing namespaces in PHP [...]

Leave a Reply