什么是PHP名称空间?
大体上什么是名称空间?
一个外行的回答和一个例子将是伟大的。
什么是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.
命名空间基本上允许您将代码放入容器中。这将防止使用相同名称的两个函数(以及类和变量)出现问题。
这在大型应用程序中非常有用,可以防止代码段共享相同名称的问题。
例如,假设我们需要两个名为“TheMessage”的函数。这两者都将分别打印(回显)不同的消息。 通常,这将导致语法错误,因为您不能有两个具有相同名称的函数。
要解决这个问题,可以将这些函数放到单独的名称空间中。这将允许您使用两个函数而不会出现任何错误。
命名空间是控制程序中名称的简单系统。 它确保名称是唯一的,不会导致任何冲突。
命名空间的工作方式类似于目录。您知道如何将文件放在与父目录(或任何其他目录)中的文件名称相同的目录中吗?好吧,命名空间让你在应用程序中为变量、函数和类做到这一点。
不久前,PHP中出现了一种趋势,即大量的静态函数类。调用这些函数的唯一方法是在调用前加上类名。这是对名称空间的一种原始尝试,但没有多少好处。
命名空间用于封闭一组代码,以便它们可以在不同的地方使用而不会发生名称冲突。 把它看作jQuery无冲突方法,你会更好地理解它。