PHP 5.3.0 was officially released on 30 June 2009 as the next-generation web programming language. The new release is one of the biggest revisions in the history of PHP. In this series I will introduce the main features. Part I deals with namespaces.
Namespaces
One of the most discussed features of PHP are the namespaces that were originally planned for the first final release of PHP 5, but had been removed due to technical problems. Namespaces help avoiding naming conflicts between classes in complex applications and methods (hint: the keyword function in a class context stands for a method). Until now, these conflicts could be resolved only by unique prefixes of class and method names, which has often led to inelegant names. The backslash was appointed to separate the components of a namespace, because this is the only character which does not collide with other reserved PHP specific tokens. A namespace is defined by the keyword namespace:
Example 1
namespace Triona {
class Order {
public function getOrder() {
}
}
}
Example 2
namespace Triona\Consulting;
class Order {
private $order;
public function getMandatoryOrder() {
return $this->order;
}
}
In the second definition it is visible, that the curly brackets can be omitted. Each class can be called by its fully qualified name, e.g. Triona\Consulting\Order. A non-qualified class name is searched in the current namespace.
Now we would like to instantiate an object in another namespace not necessarily by its fully qualified name. PHP 5.3 offers a remedy by defining an alias:
namespace Another {
use Triona\Consulting\Order as Order;
$order = new Order();
$order->getMandatoryOrder();
}
As we can see, the class Triona\Consulting\Order within the namespace Another is reachable by using Order. Namespaces bestrides not only classes, but also methods and constants. However, there are two important differences. First of all, it’s not possible to define methods using use-statement aliases. You have to be satisfied with the existing name and there is no way to introduce aliases to resolve name conflicts. Secondly, classes are always searched in the current namespace and a fatal error occurs if they are not to find there. Homonymous methods, that are not available in the current namespace, will be invoked in the global namespace. The new magic constant __NAMESPACE__ reveals in what namespace you currently linger.