What happens when a namespace and class share a name in PHP?

When using the PEAR and Zend pseudo-name template, class hierarchies are usually found that look like this:

Zend/ Db.php Db/ Expr.php 

Where DB.php contains a class named Zend_Db and Expr.php contains a class named Zend_Db_Expr . However, when you try to convert the old psuedo 5.2 namespace to the PHP 5.3 namespace, you are given the case where the namespace and class have a common name. Since the use statement can import a namespace or class name, this leads to ambiguity.

Here is an example application I'm working on:

 App/ Core.php Core/ Autoloader.php 

Here, the base directory and namespace is the application. At the top level of the namespace is the Core class:

 namespace App; class Core { } 

The Core directory contains various other base classes, some of which use the core Core . According to the pseudo-namespace pattern, this is not a problem. But in a real namespacing template, it creates the following situation:

 namespace App\Core; use App\Core as Core; // What is this importing? Namespace or class? class Autoloader { public function __construct(Core $core) {} } 

Is it determined? What is imported here?

+7
source share
1 answer

Just both. This is not a real import, just a hint to the compiler that every encounter of this alias in class-related operations should be extended to this declaration. The php namespace is just part of the class, so just think of it like this.

 $alias = 'Zend_Db'; $zendDB = new $alias; $aliasExpr = $alias . '_Expr'; $expr = new $aliasExpr; 
+1
source

All Articles