Ewout
Ewout

Reputation: 2478

PHP Namespace alias conflict?

I'm using different versions of a similar library across several projects. The libraries are namespaced like this:

Project A:

namespace Ewout\Project_A\Compatibility;
Class Core {}

Project B:

namespace Ewout\Project_B\Compatibility;
Class Core {}

...etc

To avoid using the complete namespace everywhere, I alias them in the project's PHP files:

Project A (a/main.php):

use Ewout\Project_A\Compatibility\Core as CoreX;

Project B (b/main.php):

use Ewout\Project_B\Compatibility\Core as CoreX;

Is this ok? The project scripts can be loaded simultaneously although I would never need to alias the Project_A\Compatibility\Core and Project_B\Compatibility\Core class in the same file. There is noCoreX class in the global namespace (from my tests it looks like that wouldn't cause any issues either though?).

I tested and haven't seen any errors from PHP complaining about conflicts yet, but want to make sure that this will not cause problems down the road.

Upvotes: 1

Views: 996

Answers (1)

Ewout
Ewout

Reputation: 2478

Doing further tests I can confirm that this doesn't cause any issues. PHP handles the aliases on a per-file basis, so aliases in one file do not affect aliases in another, even when included into a main script.

Furthermore, and this helps to understand the underlying process:

How does an unqualified class name like name resolve?

Class names that do not contain a backslash like name can be resolved in 2 different ways.

If there is an import statement that aliases another name to name, then the import alias is applied.

Otherwise, the current namespace name is prepended to name.

This means that when there's a class in the global namespace with the same name as the alias, this will not cause any direct conflicts, it will simply prioritize the alias over the global namespace class.

More useful information in the PHP docs: FAQ: things you need to know about namespaces

Upvotes: 1

Related Questions