what is php namespace? Detailed explanation of namespace usage examples

伊谢尔伦
Release: 2023-03-12 06:44:01
Original
1214 people have browsed it

PHP starts to support namespace in versions after 5.3.0. What is a namespace? Broadly speaking, a namespace is a way of encapsulating things. This abstract concept can be found in many places.

Namespace Overview

In PHP, namespaces are used to solve problems encountered when creating reusable code such as classes or functions when writing class libraries or applications. Two types of problems:

Name conflicts between user-written code and PHP internal classes/functions/constants or third-party classes/functions/constants.
Create an alias (or short) name for a very long identifier name (usually defined to alleviate the first type of problem) to improve the readability of the source code.
PHP namespaces provide a way to group related classes, functions, and constants together. Here is an example illustrating PHP namespace syntax:

Defining a namespace

Although any legal PHP code can be included in a namespace , but only three types of code are affected by namespaces, they are: classes, functions and constants. Namespaces are declared using the keyword namespace. If a file contains a namespace, it must declare the namespace before all other code. 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. Of course you can also define multiple namespaces in the same file.

namespace MyProject;
class MyClass
{
    #code...
}
Copy after login

Define sub-namespaces: Much like the relationship between directories and files, PHP namespaces also allow you to specify hierarchical namespace names. Therefore, the name of the namespace can be defined in a hierarchical manner:

namespace MyProject\helper\http;
class MyClass
{
    #code...
}
Copy after login

Defining multiple namespaces in the same file: There are two ways to declare multiple namespaces in the same file, but in practice In programming practice, it is highly discouraged to define the Dogo namespace in the same file. This method is mainly used to combine multiple PHP scripts in the same file. The first method is listed below.

namespace MyProject\helper\http;
class MyClass
{
    #code...
}
namespace MyProject\helper\request;
class MyClass
{
    #code...
}
Copy after login

However, it is strongly not recommended to use this method. You can refer to the following brace definition method:

namespace MyProject\helper\http;
{
    class MyClass
    {
        #code...
    }
}
namespace MyProject\helper\request;
{
    class MyClass
    {
        #code...
    }
}
Copy after login

Use elements in the PHP namespace

Before discussing how to use namespaces, you must understand how PHP knows which elements in the namespace to use. A class name can be referenced in three ways: as an unqualified name, or as a class name without a prefix, such as $a=new foo(); or foo::staticmethod();. If the current namespace is

current

namespace, 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. Warning: If a function or constant in the namespace is undefined, the unqualified function name or constant name will be resolved to a global function name or constant name. See Using Namespaces: Fallback Global Function Names/Constant Names for details. Qualified name, or name containing a prefix, such as $a = new subnamespace\foo(); or subnamespace\foo::staticmethod();. If the current namespace is currentnamespace, foo will be resolved to currentnamespace\subnamespace\foo. If the code using foo is global, code not contained in any namespace, foo will be resolved to subnamespace\foo.

Fully qualified name, or a name that includes the global prefix

operator

, for example, $a = new \currentnamespace\foo(); or \currentnamespace\foo::staticmethod(); . In this case, foo is always resolved to the literal name currentnamespace\foo in the code. Using namespaces: Aliases/Import
Allowing external fully qualified names to be referenced or imported through aliases is an important feature of namespaces. PHP namespace support There are two ways to use aliases or imports: using aliases for class names, or using aliases for namespace names. In PHP, aliases are implemented through the operator use.

Note that PHP does not support imported functions or constants.

namespace foo;
use My\Full\Classname as Another;
// 下面的例子与 use My\Full\NSname as NSname 相同
use My\Full\NSname;
// 导入一个全局类
use \ArrayObject;
Copy after login

Name resolution rules

Before explaining the name resolution rules, let’s look at some important definitions:

Unqualified nameUnqualified name: name An identifier that does not contain a namespace separator, such as Foo

Qualified name: an identifier that contains a namespace separator, such as Foo\Bar

Fully qualified name: a name that contains a name space delimiter, and an identifier that starts with a namespace delimiter, such as \Foo\Bar. namespace\Foo is also a fully qualified name.
Name resolution follows the following rules:

对完全限定名称的函数,类和常量的调用在编译时解析。例如 new \A\B 解析为类 A\B。
所有的非限定名称和限定名称(非完全限定名称)根据当前的导入规则在编译时进行转换。例如,如果命名空间 A\B\C 被导入为 C,那么对 C\D\e() 的调用就会被转换为 A\B\C\D\e()。
在命名空间内部,所有的没有根据导入规则转换的限定名称均会在其前面加上当前的命名空间名称。例如,在命名空间 A\B 内部调用 C\D\e(),则 C\D\e() 会被转换为 A\B\C\D\e() 。
非限定类名根据当前的导入规则在编译时转换(用全名代替短的导入名称)。例如,如果命名空间 A\B\C 导入为C,则 new C() 被转换为 new A\B\C() 。
在命名空间内部(例如A\B),对非限定名称的函数调用是在运行时解析的。例如对函数 foo() 的调用是这样解析的:
1) 在当前命名空间中查找名为 A\B\foo() 的函数
2) 尝试查找并调用 全局(global) 空间中的函数 foo()。
在命名空间(例如A\B)内部对非限定名称或限定名称类(非完全限定名称)的调用是在运行时解析的。下面是调用 new C() 及 new D\E() 的解析过程: new C()的解析:
在当前命名空间中查找A\B\C类。
尝试自动装载类A\B\C。

new D\E()的解析:
在类名称前面加上当前命名空间名称变成:A\B\D\E,然后查找该类。
尝试自动装载类 A\B\D\E。

为了引用全局命名空间中的全局类,必须使用完全限定名称 new \C()。

Example 名称解析示例

<?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"
// 调用另一个命名空间中的
静态
方法或命名空间函数
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"
// 当前命名空间中的静态方法或函数
A\B::foo();   // 调用命名空间 "A\A" 中定义的类 "B" 的 "foo" 方法
              // 如果类 "A\A\B" 未找到,则尝试自动装载类 "A\A\B"
\A\B::foo();  // 调用命名空间 "A\B" 中定义的类 "B" 的 "foo" 方法
              // 如果类 "A\B" 未找到,则尝试自动装载类 "A\B"
?>
Copy after login


The above is the detailed content of what is php namespace? Detailed explanation of namespace usage examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!