PHP中的命名空间详细介绍
这篇文章主要介绍了PHP中的命名空间详细介绍,本文讲解了命名空间(namespace)的概念、正在使用命名空间、定义命名空间、子命名空间、从命名空间中调用代码等内容,
概述
PHP对于命名空间的支持,经历了一段艰难的旅程。幸运的是,PHP从5.3开始引入了命名空间。自从PHP引入了命名空间,PHP代码的适用结构也得到了大大的改善。许多编程语言早就有了命名空间的概念,相对于其他语言来说,PHP对于命名空间的支持,稍微有点晚了。不管如何,每一种新特性的引入都有其目的,和其他语言一样,PHP引入命名空间也主要是为了解决名字冲突的问题。
命名空间(namespace)的概念
复制代码 代码如下:
当在字符串中使用命名空间名字的时候,一定不要忘了转义\
可以将命名空间想象成一个抽屉,你可以在抽屉里放入铅笔、尺子、A4纸等,这些都是你自己的私有物品。在你的抽屉下面是别人的抽屉,别人也可以在抽屉里放入相同的物品。为了不拿错物品,你们决定在自己的抽屉上贴上标签,这样就可以清晰的看到某个物品是属于谁的了。
之前,开发者必须在类、函数和常量中添加下划线,用来使自己的代码独立其他于代码库。这相当于所有人都给自己的物品贴上标签之后,一起放入了一个更大的抽屉里。尽管这也是一种组织代码的方式,但是这种方式是非常低效的。
命名空间的到来就是为了解决这个问题。我们可以在不同的命名空间里声明相同的函数、类和常量,而不会造成名字上的冲突。本质上,命名空间无非是一种分等级标记PHP代码的方式。
正在使用命名空间
有一点需要注意的是,我们正在间接的使用命名空间。从PHP 5.3开始,所有在非用户定义的命名空间中的声明(类、函数、常量),都默认的属于全局命名空间。
全局命名空间中包含了所有PHP内部的定义,如echo()、mysqli_connect()和Exception类。由于全局命名空间并没有独立的标识名,所以它经常被成为全局空间(global space)。
定义命名空间
命名空间的定义必须是PHP文件的第一条语句。唯一允许在定义命名空间之前使用的语句是declare语句。
定义命名空间很简单,只需要使用关键字namespace即可。命名空间的名字需要遵循PHP文件中其他标识符的命名规则。
下面是定义一个命名空间的示例:
复制代码 代码如下:
namespace MyNamespace{
class Test{
}
}
如果想定义一个属于全局空间的代码块,也是使用namespace关键字,但是后面不加命名空间的名字,如下:
复制代码 代码如下:
namespace {
class Test{
}
}
我们甚至可以在一个文件中定义多个命名空间,如下:
复制代码 代码如下:
namespace MyNamespace {
}
namespace MySecondNamespace {
}
namespace {
}
我们也可以将一个命名空间分散在不同的文件中,文件包含的处理程序会自动合并他们。因此,限制大量的命名空间在同一个文件中定义是一个很好的编程实践,,就像我们通常单独为每个类定义一个单独的文件一样。
复制代码 代码如下:
有一点需要注意的是,包含命名空间代码块的{是可选的,可以用也可以不用。事实上,只要我们坚持在一个文件中只定义一个命名空间,那么我们就可以完全省略{,这样也可以使我们的代码看起来更加简洁。
子命名空间
命名空间可以遵循一个特定的层级,就像我们电脑文件系统中得目录一样。子命名空间对于将一个项目结构化尤其特别有用。例如,你的项目需要访问数据库,你可能会想将所有数据库相关的代码(如数据库异常处理等)放在同一个子目录下。
为了保持灵活性,将子命名空间放在子目录中是非常明智的做法。这会使你的代码结构更清晰,而且会使遵循PSR-0标准的autoloaders的使用变得更容易。
PHP使用反斜线\作为命名空间的分隔符,有趣的是,PHP甚至考虑过使用笑脸:)作为命名空间的分隔符。
子命名空间定义示例:
复制代码 代码如下:
namespace MyProject\Database
class Connection {
}
可以使用尽可能多的子命名空间:
复制代码 代码如下:
namespace MyProject\Blog\Auth\Handler\Social;
class Twitter {
}
有一点需要注意的是,PHP并不支持命名空间的嵌套定义,下面的代码会导致一个致命错误:Namespace declarations cannot be nested。
复制代码 代码如下:
namespace MyProject {
namespace Database {
class Connection { }
}
}
从命名空间中调用代码
如果你想在不同的命名空间中实例化一个类、调用一个函数或者使用常量,需要使用反斜线\。他们可以从三个角度被解析:
1.未限定的名字
2.限定的名字
3.完全限定的名字
未限定的名字(Unqualified Name)
这是一个类的名称,函数或常量,但是不包括任何命名的引用。如果命名空间对你来说还比较陌生,那么这就是你熟悉的角度。
复制代码 代码如下:
namespace MyProject;
class MyClass {
static function static_method()
{
echo 'Hello, world!';
}
}
// Unqualified name, resolves to the namespace you are currently in (MyProject\MyClass)
MyClass:static_method();
限定的名字(Qualified Name)
这是我们如何使用子命名空间的方式。示例如下:
复制代码 代码如下:
namespace MyProject;
require 'myproject/database/connection.php';
// Qualified name, instantiating a class from a sub-namespace of MyProject
$connection = new Database\Connection();
完全限定的名字(Fully Qualified Name)
前面所说的使用限定的名字和未限定的名字,都是相对于当前所处的命名空间来说的。以上两种方式仅可以被用来访问当前所处的命名空间和更深层次的子命名空间。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
