What is a namespace? This article will give you an in-depth understanding of namespaces in PHP. I hope it will be helpful to you.
What is a namespace?
In a broad sense, namespace is a way of encapsulating things, and this abstract concept can be seen in many places. For example, directories are used in operating systems to group related files, and they act as namespaces for the files in the directory.
As a simple example, the file foo.txt can exist in the directories /home/greg and /home/other at the same time, but two foo.txt files cannot exist in the same directory. Also, when accessing the foo.txt file outside the directory /home/greg, we must put the directory name and the directory separator before the file name, for example /home/greg/foo.txt. The application of this principle to the field of programming is the concept of namespace.
Definition of namespace
The namespace in PHP was added in PHP5.3, if you know C++ , then namespaces are nothing new. However, namespaces are still very important in PHP.
PHP namespace can solve the following two types of problems:
The difference between user-written code and PHP internal classes/functions/constants or third-party classes/functions/constants Naming conflicts between Code readability.
Although any legal PHP code can be included in the namespace, Only classes (including abstract classes and traits), interfaces, functions, and constants are affected by namespaces. The definition of a namespace needs to be declared through the keyword namespace. The syntax format is as follows:
namespace 命名空间名;
[Example] Let’s demonstrate how to define a namespace:
<?php namespace MyProject; // 定义名为 MyProject 的命名空间。 const CONNECT_OK = 1; class Myclass { /* ... */ } function Myfunc() { /* ... */ } ?>
Except for the declare statement used to define the source file encoding before declaring the namespace, all non-PHP code (including whitespace characters) cannot appear before the namespace declaration.
In addition, unlike other language features of PHP, the same namespace can be defined in multiple files, which allows the contents of the same namespace to be divided and stored in different files.
2) Define sub-namespaces Much like the relationship between directories and files, namespaces in PHP also allow you to specify hierarchical namespace names. Therefore, the name of the namespace can be defined in a hierarchical manner: namespace App\Model;
namespace App\Controller\Home;
<?php namespace MyProject\Controller\Home; // 定义名为 MyProject 的命名空间。 const CONNECT_OK = 1; class Myclass { /* ... */ } function Myfunc() { /* ... */ } ?>
You can also define multiple namespaces in one file. There are two syntax forms for defining multiple namespaces in the same file. The following is an example to demonstrate: [Example] Define multiple namespaces - simple combination syntax.
<?php namespace MyProject; const CONNECT_OK = 1; class className { /* ... */ } namespace AnotherProject; const CONNECT_OK = 1; class className { /* ... */ } ?>
[Example] Define multiple namespaces—braces { } syntax.
<?php namespace MyProject{ const CONNECT_OK = 1; class className { /* ... */ } } namespace AnotherProject{ const CONNECT_OK = 1; class className { /* ... */ } } ?>
In actual programming practice, it is not recommended to define multiple namespaces in the same file. Defining multiple namespaces is mainly used to combine multiple PHP scripts in the same file. It is recommended to use curly bracket syntax when defining multiple namespaces.
To combine the code in the global non-namespace with the code in the namespace, you can only use the syntax in the form of braces. At the same time, the global code must use a namespace statement without a name plus braces. brackets, as follows:
<?php namespace MyProject{ // 命名空间中的代码 const CONNECT_OK = 1; class className { /* ... */ } } namespace { // 命名空间外的全局代码 $obj = new MyProject\className(); } ?>
Using Namespaces: Basics
Before discussing how to use namespaces, you must understand how PHP Know which namespace to use for elements. We can make a simple analogy between the PHP namespace and the file system. There are three ways to access a file in the file system:
The relative file name format is such as foo.txt. It will be parsed as currentdirectory/foo.txt, where currentdirectory represents the current directory. Therefore, if the current directory is /home/foo, the file name is parsed as /home/foo/foo.txt;
The relative path name format is such as subdirectory/foo.txt. It will be parsed as currentdirectory/subdirectory/foo.txt;
The absolute path name format is such as /main/foo.txt. It will be parsed as /main/foo.txt.
Elements in the PHP namespace use the same principle. For example, a class name under a namespace can be referenced in three ways:
unqualified name, or a class name without a prefix, such as
$a=new foo() ;. If the current namespace is currentnamespace, then foo will be resolved to currentnamespace\foo. If the code using foo is global and does not contain code in any namespace, foo will be resolved as foo. </li><li><p>限定名称,或包含前缀的名称,例如<code>$a = new subnamespace\foo();
或subnamespace\foo::staticmethod();
。如果当前的命名空间是 currentnamespace,则 foo 会被解析为 currentnamespace\subnamespace\foo。如果使用 foo 的代码是全局的,不包含在任何命名空间中的代码,foo 会被解析为 subnamespace\foo。
完全限定名称,或包含了全局前缀操作符的名称,例如$a = new \currentnamespace\foo();
或\currentnamespace\foo::staticmethod();
。在这种情况下,foo 总是被解析为代码中的文字名 currentnamespace\foo。
警告:如果命名空间中的函数或常量未定义,则该非限定的函数名称或常量名称会被解析为全局函数名称或常量名称。
下面是一个使用这三种方式的实例,我们需要两个 PHP 源文件,分别是 demo.php 和 index.php,示例代码如下:
1) demo.php
<?php namespace Foo\Bar\Demo; const FOO = 1; function foo() {} class foo { public function demo() { echo '命名空间为:Foo\Bar\Demo'; } } ?>
2) index.php
<?php namespace Foo\Bar; include 'Demo.php'; const FOO = 2; function foo() { echo 'Foo\Bar 命名空间下的 foo 函数<br>'; } class foo { static function demo(){ echo '命名空间为:Foo\Bar<br>'; } } /* 非限定名称 */ foo(); // 解析为 Foo\Bar\foo resolves to function Foo\Bar\foo foo::demo(); // 解析为类 Foo\Bar\foo 的静态方法 staticmethod。 echo FOO.'<br>'; // 解析为常量 Foo\Bar\FOO /* 限定名称 */ Demo\foo(); // 解析为函数 Foo\Bar\Demo\foo Demo\foo::demo(); // 解析为类 Foo\Bar\Demo\foo, // 以及类的方法 demo echo Demo\FOO.'<br>'; // 解析为常量 Foo\Bar\Demo\FOO /* 完全限定名称 */ \Foo\Bar\foo(); // 解析为函数 Foo\Bar\foo \Foo\Bar\foo::demo(); // 解析为类 Foo\Bar\foo, 以及类的方法 demo echo \Foo\Bar\FOO.'<br>'; // 解析为常量 Foo\Bar\FOO ?>
运行结果如下:
Foo\Bar 命名空间下的 foo 函数 命名空间为:Foo\Bar 2 Foo\Bar\Demo 命名空间下的 foo 函数 命名空间为:Foo\Bar\Demo 1 Foo\Bar 命名空间下的 foo 函数 命名空间为:Foo\Bar 2
注意:访问任意全局类、函数或常量,都可以使用完全限定名称,例如 \strlen() 或 \Exception 等。
使用命名空间:别名/导入
PHP 允许通过别名引用或导入的方式来使用外部的命名空间,这是命名空间的一个重要特征。这有点类似于在类 unix 文件系统中可以创建对其它的文件或目录的符号连接。
使用 use 关键字可以实现命名空间的导入,从 PHP5.6 开始允许导入函数和常量,并为它们设置别名。语法格式如下:
use namespace;
在 PHP 中,别名是通过操作符 use 与 as 来实现的,语法格式如下:
use 命名空间 as 别名;
【示例】使用 use 操作符导入和使用别名。
<?php namespace foo; use My\Full\Classname as Another; // 下面的例子与 use My\Full\NSname as NSname 相同 use My\Full\NSname; // 导入一个全局类 use ArrayObject; // 导入一个函数 use function My\Full\functionName; // 导入一个函数并定义别名 use function My\Full\functionName as func; // 导入一个常量 use const My\Full\CONSTANT; $obj = new namespace\Another; // 实例化 foo\Another 对象 $obj = new Another; // 实例化 My\Full\Classname 对象 NSname\subns\func(); // 调用 My\Full\NSname\subns\func 函数 $a = new ArrayObject(array(1)); // 实例化 ArrayObject 对象 // 如果不使用 "use \ArrayObject" ,则实例化一个 foo\ArrayObject 对象 func(); // 调用 My\Full\functionName 函数 echo CONSTANT; // 打印 My\Full\CONSTANT 常量 ?>
注意:对命名空间中的名称(包含命名空间分隔符的完全限定名称,如 Foo\Bar ,以及相对的不包含命名空间分隔符的全局名称,如 FooBar)来说,前导的反斜杠是不必要的也是不推荐的,因为导入的名称必须是完全限定的,不会根据当前的命名空间作相对解析。
为了简化操作,PHP 还支持在一行中导入多个命名空间,中间使用,隔开,示例代码如下:
<?php use My\Full\Classname as Another, My\Full\NSname; $obj = new Another; // 实例化 My\Full\Classname 对象 NSname\subns\func(); // 调用 My\Full\NSname\subns\func 函数 ?>
导入操作是编译执行的,但动态的类名称、函数名称或常量名称则不是。
<?php use My\Full\Classname as Another, My\Full\NSname; $obj = new Another; // 实例化一个 My\Full\Classname 对象 $a = 'Another'; $obj = new $a; // 实际化一个 Another 对象 ?>
另外,导入操作只影响非限定名称和限定名称。完全限定名称由于是确定的,故不受导入的影响。
namespace 关键字和 __NAMESPACE__ 常量
PHP 支持两种抽象的访问当前命名空间内部元素的方法,__NAMESPACE__ 魔术常量和 namespace 关键字。
__NAMESPACE__ 常量的值是包含当前命名空间名称的字符串。在全局的,不包括在任何命名空间中的代码,它是一个空的字符串。示例代码如下:
<?php namespace App\Controller\Home; echo __NAMESPACE__; ?>
运行结果如下:
App\Controller\Home
namespace 关键字可用来显式访问当前命名空间或子命名空间中的元素,它等价于类中的 self 操作符。示例代码如下:
<?php namespace MyProject; use Foo\Bar\Demo as demo; // 导入 Foo\Bar\Demo 命名空间 blah\mine(); // 调用 MyProject\blah\mine() 函数 namespace\blah\mine(); // 调用 MyProject\blah\mine() 函数 namespace\func(); // 调用 MyProject\func() 函数 namespace\sub\func(); // 调用 MyProject\sub\func() 函数 namespace\cname::method(); // 调用 MyProject\cname 类的静态方法 method $a = new namespace\sub\cname(); // 实例化 MyProject\sub\cname 对象 $b = namespace\CONSTANT; // 将常量 MyProject\CONSTANT 的值赋给 $b ?>
命名空间名称解析规则
在说明名称解析规则之前,我们先来看看命名空间名称的定义:
非限定名称:名称中不包含命名空间分隔符的标识符,例如 Foo;
限定名称:名称中含有命名空间分隔符的标识符,例如 Foo\Bar;
完全限定名称:名称中包含命名空间分隔符,并以命名空间分隔符开始的标识符,例如 \Foo\Bar。namespace\Foo 也是一个完全限定名称。
名称解析遵循下列规则:
Search for a function named A\B\foo() in the current namespace;
Try to find and call the foo() function in the global space.
Parsing of new C():
Parsing of new D\E():
In order to refer to a global class in the global namespace, the fully qualified name new \C() must be used.
Recommended study: "PHP Video Tutorial"
The above is the detailed content of What is a namespace? Detailed explanation of namespaces in PHP. For more information, please follow other related articles on the PHP Chinese website!