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

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

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛