doufei1893 2017-02-15 13:13
浏览 68
已采纳

PHP命名空间别名冲突?

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.

  • 写回答

1条回答 默认 最新

  • dongzhong5573 2017-02-21 11:50
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP