PHP namespace resolution rules
Namespace name definition
Unqualified name
<code>名称中不包含命名空间分隔符的标识符,例如Foo </code>
Qualified nameQualified name
<code>名称中含有命名空间分隔符的标识符,例如:Foo\Bar </code>
Fully qualified name
<code>名称中包含命名空间分隔符,并以命名空间分隔符开始的标识符,例如:\Foo\Bar. namespace\Foo 也是一个完全限定名称。 </code>
Name resolution follows the following rules
Calls to unqualified names or qualified name classes (non-fully qualified names) inside a namespace (e.g. AB) are resolved at runtime. The following is the parsing process of calling new C() and new DE():
Parsing of new C():
Find class ABC in the current namespace;
Try to automatically load class ABC.
new DE() analysis:
Add the current namespace name in front of the class name to become: ABDE, and then find the class
Try to automatically load the class ABDE.
In order to refer to a global class in the global namespace, the fully qualified name new C() must be used.
Name resolution example
<code><?php namespace A; use B\D, C\E as F; // 函数调用 foo(); // 首先尝试调用定义在命名空间"A"中的函数foo() // 再尝试调用全局函数 "foo" \foo(); // 调用全局空间函数 "foo" my\foo(); // 调用定义在命名空间"A\my"中函数 "foo" F(); // 首先尝试调用定义在命名空间"A"中的函数 "F" // 再尝试调用全局函数 "F" // 类引用 new B(); // 创建命名空间 "A" 中定义的类 "B" 的一个对象 // 如果未找到,则尝试自动装载类 "A\B" new D(); // 使用导入规则,创建命名空间 "B" 中定义的类 "D" 的一个对象 // 如果未找到,则尝试自动装载类 "B\D" new F(); // 使用导入规则,创建命名空间 "C" 中定义的类 "E" 的一个对象 // 如果未找到,则尝试自动装载类 "C\E" new \B(); // 创建定义在全局空间中的类 "B" 的一个对象 // 如果未发现,则尝试自动装载类 "B" new \D(); // 创建定义在全局空间中的类 "D" 的一个对象 // 如果未发现,则尝试自动装载类 "D" new \F(); // 创建定义在全局空间中的类 "F" 的一个对象 // 如果未发现,则尝试自动装载类 "F" // 调用另一个命名空间中的<strong>静态方法</strong>或命名空间函数 B\foo(); // 调用命名空间 "A\B" 中函数 "foo" B::foo(); // 调用命名空间 "A" 中定义的类 "B" 的 "foo" 方法 // 如果未找到类 "A\B" ,则尝试自动装载类 "A\B" D::foo(); // 使用导入规则,调用命名空间 "B" 中定义的类 "D" 的 "foo" 方法 // 如果类 "B\D" 未找到,则尝试自动装载类 "B\D" \B\foo(); // 调用命名空间 "B" 中的函数 "foo" \B::foo(); // 调用全局空间中的类 "B" 的 "foo" 方法 // 如果类 "B" 未找到,则尝试自动装载类 "B" // 当前命名空间中的<strong>静态方法</strong>或函数 A\B::foo(); // 调用命名空间 "A\A" 中定义的类 "B" 的 "foo" 方法 // 如果类 "A\A\B" 未找到,则尝试自动装载类 "A\A\B" \A\B::foo(); // 调用命名空间 "A\B" 中定义的类 "B" 的 "foo" 方法 // 如果类 "A\B" 未找到,则尝试自动装载类 "A\B" ?> </code>
The above introduces the PHP namespace parsing rules, including static methods. I hope it will be helpful to friends who are interested in PHP tutorials.