PHP命名空间别名冲突?
PHP Namespace alias conflict?
我在多个项目中使用了类似库的不同版本。这些库的命名空间如下:
项目 A:
namespace Ewout\Project_A\Compatibility;
Class Core {}
项目 B:
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\Core
和 Project_B\Compatibility\Core
class 添加别名。全局命名空间中没有CoreX
class(从我的测试看来这也不会引起任何问题?)。
我进行了测试,但尚未发现 PHP 抱怨冲突的任何错误,但我想确保这不会在以后造成问题。
做进一步的测试我可以确认这不会导致任何问题。 PHP 在 per-file 的基础上处理别名,因此一个文件中的别名不会影响另一个文件中的别名,即使包含在主脚本中也是如此。
此外,这有助于理解底层过程:
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.
这意味着当全局命名空间中有一个 class 与别名同名时,这不会导致任何直接冲突,它只是将别名优先于全局命名空间 class.
PHP 文档中的更多有用信息:FAQ: things you need to know about namespaces
我在多个项目中使用了类似库的不同版本。这些库的命名空间如下:
项目 A:
namespace Ewout\Project_A\Compatibility;
Class Core {}
项目 B:
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\Core
和 Project_B\Compatibility\Core
class 添加别名。全局命名空间中没有CoreX
class(从我的测试看来这也不会引起任何问题?)。
我进行了测试,但尚未发现 PHP 抱怨冲突的任何错误,但我想确保这不会在以后造成问题。
做进一步的测试我可以确认这不会导致任何问题。 PHP 在 per-file 的基础上处理别名,因此一个文件中的别名不会影响另一个文件中的别名,即使包含在主脚本中也是如此。
此外,这有助于理解底层过程:
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.
这意味着当全局命名空间中有一个 class 与别名同名时,这不会导致任何直接冲突,它只是将别名优先于全局命名空间 class.
PHP 文档中的更多有用信息:FAQ: things you need to know about namespaces