什么是PHP名称空间?
大体上什么是名称空间?
一个外行的回答和一个例子将是伟大的。
什么是PHP名称空间?
大体上什么是名称空间?
一个外行的回答和一个例子将是伟大的。
当前回答
就像目录和文件一样,PHP中的命名空间用于对类、函数、接口和常量进行分组。
例子:
Filesystem | PHP Namespace
----------------|------------------
/Dir/File.txt | \Namespace\Class
它提供了一种包装来自全局空间的项的方法,并允许使用普通项名而不会在程序中引起名称冲突。 PHP 5.3.0和PHP 7支持它。
但是PHP命名空间与基于Unix的文件系统的类比存在一定的局限性:
| Filesystem | PHP Namespace
--------------------------|-----------------------|-------------------------
Cas sensitive | No | Yes
--------------------------|-----------------------|-------------------------
Name with plain number | Yes | No
--------------------------|-----------------------|-------------------------
Path level | Yes | Yes
--------------------------|-----------------------|-------------------------
Plain metacharacters name | Yes | No
该原理扩展到编程词中的命名空间。
其他回答
在其他编程语言中有一些技术,比如名称空间(比如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.
命名空间允许您将一堆代码放在一个名称下,并且不会与类、函数和常量发生任何命名冲突。
它允许您的代码驻留在该名称空间中。
PHP使用有点争议的字符\来显示名称空间级别。人们很愤怒,因为它也被用作转义字。
要在PHP中使用名称空间,请在文件顶部使用如下内容。
namespace my\namespace;
您可以在关于名称空间的官方PHP文档中找到更多信息。
Namespace就像将许多东西打包到一个包中。将命名空间想象成一个抽屉,您可以在其中放各种东西:一支铅笔、一把尺子、一张纸等等。为了避免使用彼此的物品,你们决定在抽屉上贴上标签,这样就能清楚地知道什么东西属于谁。
命名空间用于封闭一组代码,以便它们可以在不同的地方使用而不会发生名称冲突。 把它看作jQuery无冲突方法,你会更好地理解它。
命名空间是控制程序中名称的简单系统。 它确保名称是唯一的,不会导致任何冲突。