gpt4 book ai didi

PHP命名空间别名冲突?

转载 作者:行者123 更新时间:2023-12-04 16:55:49 25 4
gpt4 key购买 nike

我在多个项目中使用不同版本的类似库。这些库的命名空间如下:

项目A:

namespace Ewout\Project_A\Compatibility;
Class Core {}

项目乙:
namespace Ewout\Project_B\Compatibility;
Class Core {}

...等等

为了避免在任何地方使用完整的命名空间,我在项目的 PHP 文件中给它们起了别名:

项目 A (a/main.php):
use Ewout\Project_A\Compatibility\Core as CoreX;

项目 B (b/main.php):
use Ewout\Project_B\Compatibility\Core as CoreX;

这个可以吗?项目脚本可以同时加载,尽管我永远不需要别名 Project_A\Compatibility\CoreProject_B\Compatibility\Core同一个文件中的类。没有 CoreX全局命名空间中的类(从我的测试来看,这看起来也不会导致任何问题?)。

我测试过,还没有看到任何来自 PHP 提示冲突的错误,但我想确保这不会导致问题。

最佳答案

做进一步的测试我可以确认这不会导致任何问题。 PHP 在每个文件的基础上处理别名,因此一个文件中的别名不会影响另一个文件中的别名,即使包含在主脚本中也是如此。

此外,这有助于理解底层过程:

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.



这意味着当全局命名空间中有一个与别名同名的类时,这不会引起任何直接的冲突,它只是将别名优先于全局命名空间类。

PHP 文档中的更多有用信息: FAQ: things you need to know about namespaces

关于PHP命名空间别名冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42250408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com