Friday, September 28th, 2007
Namespaces in PHP 6!
Well, your alternate language fanboys/flameboys will have one less things to throw at PHP Savants when an Armageddon-like debate is held yet about how PHP is a bad language. It has been a while, and I am 6 weeks late to make a post about it, but there’s been some exciting news in PHP - WE NOW HAVE NAMESPACES!!!! - Well for PHP 6 anyway.
It means no more workaround implementation which made class names look like:
{
}
Instead, we can now have:
class SomeGateway
{
public function getSomeData()
{
return array(’some’=>‘data’);
}
}
How does one create an instance of a class?
It may take a little getting used to, but this could pretty much be the way to access it. Or at least it says so in some examples.
$data = $someGateway->getSomeData();
OR
$gateway = new SomeGateway();
Here’s an excerpt from the README.namespace file on the PHP CVS.
snip
…
In global namespace __NAMESPACE__ constant has the value of empty string.
Names inside namespace are resolved according to the following rules:
1) all qualified names are translated during compilation according to
current import rules. So if we have “import A::B::C” and then “C::D::e()”
it is translated to “A::B::C::D::e()”.
2) unqualified class names translated during compilation according to
current import rules. So if we have “import A::B::C” and then “new C()” it
is translated to “new A::B::C()”.
3) inside namespace, calls to unqualified functions that are defined in
current namespace (and are known at the time the call is parsed) are
interpreted as calls to these namespace functions.
4) inside namespace, calls to unqualified functions that are not defined
in current namespace are resolved at run-time. The call to function foo()
inside namespace (A::B) first tries to find and call function from current
namespace A::B::foo() and if it doesn’t exist PHP tries to call internal
function foo(). Note that using foo() inside namespace you can call only
internal PHP functions, however using ::foo() you are able to call any
function from the global namespace.
5) unqualified class names are resolved at run-time. E.q. “new Exception()”
first tries to use (and autoload) class from current namespace and in case
of failure uses internal PHP class. Note that using “new A” in namespace
you can only create class from this namespace or internal PHP class, however
using “new ::A” you are able to create any class from the global namespace.
6) Calls to qualified functions are resolved at run-time. Call to
A::B::foo() first tries to call function foo() from namespace A::B, then
it tries to find class A::B (__autoload() it if necessary) and call its
static method foo()
7) qualified class names are interpreted as class from corresponding
namespace. So “new A::B::C()” refers to class C from namespace A::B.
…
/snip
For more information, check out - http://cvs.php.net/viewvc.cgi/php-src/README.namespaces?view=markup