什么是PHP名称空间?

大体上什么是名称空间?

一个外行的回答和一个例子将是伟大的。


当前回答

在其他编程语言中有一些技术,比如名称空间(比如Java中的包)。它们被用来在一个项目中拥有多个具有相同名称的类。

来自php文档(http://www.php.net/manual/en/language.namespaces.rationale.php):

What are namespaces? In the broadest definition namespaces are a way of encapsulating items. This can be seen as an abstract concept in many places. For example, in any operating system directories serve to group related files, and act as a namespace for the files within them. As a concrete example, the file foo.txt can exist in both directory /home/greg and in /home/other, but two copies of foo.txt cannot co-exist in the same directory. In addition, to access the foo.txt file outside of the /home/greg directory, we must prepend the directory name to the file name using the directory separator to get /home/greg/foo.txt. This same principle extends to namespaces in the programming world.

其他回答

在其他编程语言中有一些技术,比如名称空间(比如Java中的包)。它们被用来在一个项目中拥有多个具有相同名称的类。

来自php文档(http://www.php.net/manual/en/language.namespaces.rationale.php):

What are namespaces? In the broadest definition namespaces are a way of encapsulating items. This can be seen as an abstract concept in many places. For example, in any operating system directories serve to group related files, and act as a namespace for the files within them. As a concrete example, the file foo.txt can exist in both directory /home/greg and in /home/other, but two copies of foo.txt cannot co-exist in the same directory. In addition, to access the foo.txt file outside of the /home/greg directory, we must prepend the directory name to the file name using the directory separator to get /home/greg/foo.txt. This same principle extends to namespaces in the programming world.

命名空间对函数和类的作用就像作用域对变量的作用一样。它允许您在同一程序的不同部分使用相同的函数或类名,而不会引起名称冲突。

简单地说,可以将名称空间看作一个人的姓氏。如果有两个人叫“约翰”,你可以用他们的姓氏来区分他们。

的场景

假设您编写了一个使用名为output()的函数的应用程序。output()函数获取页面上的所有HTML代码并将其发送给用户。

稍后,应用程序变得更大,您希望添加新功能。您添加了一个允许生成RSS提要的库。这个库还使用一个名为output()的函数来输出最终提要。

当您调用output()时,PHP如何知道是使用您的output()函数还是RSS库的output()函数?它不是。除非您正在使用名称空间。

例子

我们如何解决有两个output()函数?简单。我们将每个output()函数置于其自己的名称空间中。

它看起来是这样的:

namespace MyProject;

function output() {
    # Output HTML page
    echo 'HTML!';
}

namespace RSSLibrary;

function output(){
    # Output RSS feed
    echo 'RSS!';
}

稍后,当我们想要使用不同的函数时,我们可以使用:

\MyProject\output();
\RSSLibrary\output();

或者我们可以声明我们在其中一个命名空间中,然后我们可以调用该命名空间的output():

namespace MyProject;

output(); # Output HTML page
\RSSLibrary\output();

没有命名空间?

如果没有命名空间,每次添加库时就必须(潜在地)修改大量代码,或者提出冗长的前缀以使函数名惟一。使用名称空间,我们可以避免在将第三方代码与自己的项目混合时产生命名冲突的麻烦。

命名空间用于封闭一组代码,以便它们可以在不同的地方使用而不会发生名称冲突。 把它看作jQuery无冲突方法,你会更好地理解它。

Namespace就像将许多东西打包到一个包中。将命名空间想象成一个抽屉,您可以在其中放各种东西:一支铅笔、一把尺子、一张纸等等。为了避免使用彼此的物品,你们决定在抽屉上贴上标签,这样就能清楚地知道什么东西属于谁。

命名空间是控制程序中名称的简单系统。 它确保名称是唯一的,不会导致任何冲突。