Daniel Bingham
Daniel Bingham

Reputation: 12914

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

When using the pseudo namespacing pattern of PEAR and Zend, it is common to come across class heirarchies 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 5.2 psuedo namespacing into PHP 5.3 namespacing you are presented with a case where a namespace and a class share a name. Since the use operator can import either a namespace or a classname this leads to ambiguity.

Here's an example of an app I'm working on converting:

App/
    Core.php
    Core/
        Autoloader.php

Here the base directory and namespace are App. In the top level of the name space is a Core class:

namespace App;
class Core { }

In the Core directory are various other core classes, some of which use the main Core. Under the pseudo namespacing pattern, this isn't a problem. But in the real namespacing pattern it creates this situation:

namespace App\Core;
use App\Core as Core;  // What is this importing?  Namespace or class?

class Autoloader {
    public function __construct(Core $core) {}
}

Is this defined? What is actually imported here?

Upvotes: 7

Views: 230

Answers (1)

dev-null-dweller
dev-null-dweller

Reputation: 29462

Simply both. It is not real import, just a hint for compiler, that every encounter of this alias in class related operations should be expanded to this declaration. In php namespace is just part of class so just think of it like this

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

Upvotes: 1

Related Questions