简体   繁体   English

php名称空间:需要限定哪些条件?

[英]php namespaces: what needs to be qualified?

I am new to using namespaces in PHP and they seem very simple. 我刚开始在PHP中使用名称空间,它们看起来非常简单。 However, when I added a namespace to the top of a large file containing classes, interfaces, and closures, the code stopped working altogether. 但是,当我在包含类,接口和闭包的大文件的顶部添加名称空间时,代码完全停止工作。 Apparently some elements are not qualified properly. 显然,某些元素的资格不正确。

For example: 例如:

<?php
namespace MyNamespace;
interface MyInterface { ... }
class MyClass implements MyInterface { ... }
...

I read the documentation at php.net, but I couldn't find a simple list of elements that require qualification under a single named space (either globally or otherwise). 我在php.net上阅读了文档,但是找不到在单个命名空间(全局或其他)下需要限定的元素的简单列表。

So my question is, if you simply declare a namespace at the top of an otherwise namespace-free file, what elements would require qualification in that scenario? 所以我的问题是,如果您只是在一个没有名称空间的文件的顶部声明一个名称空间,那么在这种情况下哪些元素需要限定?

The way you have it now with everything in one file like that, every class, interface or function in that file is now in the MyNamespace namespace. 现在,将所有内容都保存在一个文件中的方式是,该文件中的每个类,接口或函数现在都位于MyNamespace命名空间中。 So from within those classes, interfaces and functions, if you want to refer to a class that is in a different namespace (global or named) you must use it's fully qualified name (or use use statements to declare aliases at top of the file). 因此,在这些类,接口和函数中,如果要引用位于不同名称空间(全局或命名)中的类,则必须使用其全限定名(或使用use语句在文件顶部声明别名) 。 Note: pre-pending a \\ will get you to the global namespace. 注意:前置\\将使您进入全局名称空间。

Additionally, from outside of the file, if you want to access one of those classes, interfaces or functions you must use the fully qualified name. 此外,从文件外部,如果要访问这些类,接口或函数之一,则必须使用标准名称。

MyNamespace\MyInterface
MyNamespace\MyClass

I should also mention, this is not a typical set up. 我还要提到,这不是典型的设置。 According to psr standards, you should have only 1 class per file. 根据psr标准,每个文件应该只有1个类。 Take a look at http://www.php-fig.org/ for more guidance on standards and practices. 请访问http://www.php-fig.org/了解有关标准和实践的更多指南。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM