Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

namespaces

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?

like image 503
Daniel Bingham Avatar asked Nov 12 '12 17:11

Daniel Bingham


People also ask

What does namespace do in PHP?

In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.

What is PHP namespace class?

Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task. They allow the same name to be used for more than one class.

Can I use two namespace in PHP?

Multiple namespaces may also be declared in the same file. There are two allowed syntaxes. This syntax is not recommended for combining namespaces into a single file. Instead it is recommended to use the alternate bracketed syntax.

What is the difference between namespace and use in PHP?

Namespace is to avoid class name collisions, so you can have two same class names under two different namespaces. Use is just like PHP include. Please sign in or create an account to participate in this conversation.


1 Answers

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;
like image 58
dev-null-dweller Avatar answered Nov 09 '22 11:11

dev-null-dweller