Home Backend Development PHP Tutorial PHP 5.3新特性命名空间规则解析及高级功能_PHP

PHP 5.3新特性命名空间规则解析及高级功能_PHP

Jun 01, 2016 pm 12:19 PM
php Namespaces

日前发布的PHP 5.3中,最重要的一个新特性就是命名空间的加入。本文介绍了PHP命名空间的一些术语,其解析规则,以及一些高级功能的应用,希望能够帮助读者在项目中真正使用命名空间。

在这里中我们介绍了PHP命名空间的用途和namespace关键字,在这篇文章中我们将介绍一下use命令的使用以及PHP如何解析命名空间的名字的。

为了便于对比,我定义了两个几乎一样的代码块,只有命名空间的名字不同。

  1. // application library 1  
  2. namespace App\Lib1;  
  3. const MYCONST = 'App\Lib1\MYCONST';  
  4. function MyFunction() {  
  5.  return __FUNCTION__;  
  6. }  
  7. class MyClass {  
  8.  static function WhoAmI() {  
  9. eturn __METHOD__;  
  10.  }  
  11. }  
  12. ?>
lib2.php

  1. // application library 2  
  2. namespace App\Lib2;  
  3. const MYCONST = 'App\Lib2\MYCONST';  
  4. function MyFunction() {  
  5.  return __FUNCTION__;  
  6. }  
  7. class MyClass {  
  8.  static function WhoAmI() {  
  9. eturn __METHOD__;  
  10.  }  
  11. }  
  12. ?> 

开始之前先要理解几个PHP命名空间相关术语。

◆完全限定名称(Fully-qualified name)

任何PHP代码都可以引用完全限定名称,它是一个以命名空间反斜线开头的标识符,如\App\Lib1\MYCONST,\App\Lib2\MyFunction( )等。

完全限定名称是没有任何歧义的,开头的反斜线和文件路径的作用有点类似,它表示“根”全局空间,如果我们在全局空间中实现了一个不同的MyFunction( ),可以使用\MyFunction( )从lib1.php或lib2.php调用它。

完全限定名称对一次性函数调用或对象初始化非常有用,但当你产生了大量的调用时它们就没有实用价值了,在下面的讨论中我们将会看到,PHP提供了其它选项以解除我们为命名空间打字的烦恼。

◆限定名称(Qualified name)

至少有一个命名空间分隔符的标识符,如Lib1\MyFunction( )。

◆非限定名称(Unqualified name)

没有命名空间分隔符的标识符,如MyFunction( )。

在相同的命名空间内工作

仔细思考下面的代码:

myapp1.php

<ol class="dp-c">
<li class="alt">namespace App\Lib1;  </li>
<li class="alt"> </li>
<li>
<strong><font color="#006699">require_once</font></strong>(<font color="#0000ff">'lib1.php'</font>);  </li>
<li class="alt">
<strong><font color="#006699">require_once</font></strong>(<font color="#0000ff">'lib2.php'</font>);  </li>
<li> </li>
<li class="alt">header(<font color="#0000ff">'Content-type: text/plain'</font>);  </li>
<li>echo MYCONST . <font color="#0000ff">"\n"</font>;  </li>
<li class="alt">echo MyFunction() . <font color="#0000ff">"\n"</font>;  </li>
<li>echo MyClass::WhoAmI() . <font color="#0000ff">"\n"</font>;  </li>
<li class="alt">?>  <br>
</li>
</ol>
Copy after login

即使我们同时包括了lib1.php和lib2.php,MYCONST,MyFunction和MyClass标识符只能在lib1.php中引用,这是因为myapp1.php的代码在相同的App\Lib1命名空间内。

执行结果:

  1. App\Lib1\MYCONST  
  2. App\Lib1\MyFunction  
  3. App\Lib1\MyClass::WhoAmI  

命名空间导入

可以使用use操作符导入命名空间,如:

myapp2.php

 
  • use App\Lib2;  
  • require_once('lib1.php');  
  • require_once('lib2.php');  
  • header('Content-type: text/plain');  
  • echo Lib2\MYCONST . "\n";  
  • echo Lib2\MyFunction() . "\n";  
  • echo Lib2\MyClass::WhoAmI() . "\n";  
  • ?>
  •  

    可以定义任意数量的use语句,或使用逗号分隔成独立的命名空间,在这个例子中我们导入了App\Lib2命名空间,但我们仍然不能直接引用 MYCONST,MyFunction和MyClass,因为我们的代码还在全局空间中,但如果我们添加了“Lib2\”前缀,它们就变成限定名称 了,PHP将会搜索导入的命名空间,直到找到匹配项。

    执行结果:

    1. App\Lib2\MYCONST  
    2. App\Lib2\MyFunction  
    3. App\Lib2\MyClass::WhoAmI 

    命名空间别名

    命名空间别名可能是最有用的构想了,别名允许我们使用较短的名称引用很长的命名空间。

    myapp3.php

    1. use App\Lib1 as L;  
    2. use App\Lib2\MyClass as Obj;  
    3. header('Content-type: text/plain');  
    4. require_once('lib1.php');  
    5. require_once('lib2.php');  
    6. echo L\MYCONST . "\n";  
    7. echo L\MyFunction() . "\n";  
    8. echo L\MyClass::WhoAmI() . "\n";  
    9. echo Obj::WhoAmI() . "\n";  
    10. ?>  

    第一个use语句将App\Lib1定义为“L”,任何使用“L”的限定名称在编译时都会被翻译成“App\Lib1”,因此我们就可以引用L\MYCONST和L\MyFunction而不是完全限定名称了。

    第二个use语句定义了“obj”作为App\Lib2\命名空间中MyClass类的别名,这种方式只适合于类,不能用于常量和函数,现在我们就可以使用new Obj( )或象上面那样运行静态方法了。

    执行结果:

    1. App\Lib1\MYCONST  
    2. App\Lib1\MyFunction  
    3. App\Lib1\MyClass::WhoAmI  
    4. App\Lib2\MyClass::WhoAmI  

    PHP命名解析规则

    PHP标识符名称使用下列命名空间规则进行解析,请参考PHP用户手册了解更详细的信息:

    1.在编译时调用完全限定函数、类或常量;

    2.非限定名称和限定名称根据导入规则进行翻译,例如,如果A\B\C导入为C,调用C\D\e( )就会被翻译成A\B\C\D\e( );

    3.在PHP命名空间内,所有限定名称尚未根据导入规则转换,例如,如果在命名空间A\B中调用C\D\e( ),那么会被翻译成A\B\C\D\e( );

    4.非限定类名称根据当前的导入规则进行转换,使用全名替换导入的短名称,例如,如果类C在命名空间A\B中被导入为X,那么new X( )就会被翻译为new A\B\C( );

    5.在命名空间中非限定函数调用在运行时解析,例如,如果MyFunction( )在命名空间A\B中被调用,PHP首先会查找函数\A\B\MyFunction( ),如果没有找到,然后会在全局空间中查找\MyFunction( );

    6.调用非限定或限定类名在运行时被解析,例如,如果我们在命名空间A\B中调用new C( ),PHP将会查找类A\B\C,如果没有找到,PHP会尝试自动载入A\B\C。


    PHP命名空间高级特性

    接下来让我们看一看PHP命名空间的一些高级特性。

    __NAMESPACE__常量

    __NAMESPACE__是一个PHP字符串,它总是返回当前命名空间的名称,在全局空间中它是一个空字符串。

    <ol class="dp-c">
    <li class="alt">namespace App\Lib1;  </li>
    <li class="alt">echo __NAMESPACE__; <font color="#008200">// outputs: App\Lib1 </font> </li>
    <li>?>  </li>
    <li class="alt"> </li>
    </ol>
    Copy after login

    这个值在调试时非常有用,它也可由于动态生成一个完全限定类名,如:

    <ol class="dp-c">
    <li class="alt">namespace App\Lib1;  </li>
    <li class="alt"> </li>
    <li>
    <strong><font color="#006699">class</font></strong> MyClass {  </li>
    <li class="alt"> <strong><font color="#006699">public</font></strong> <strong><font color="#006699">function</font></strong> WhoAmI() {  </li>
    <li>
    <strong><font color="#006699">return</font></strong> <strong><font color="#006699">__METHOD__</font></strong>;  </li>
    <li class="alt"> }  </li>
    <li>}  </li>
    <li class="alt"> </li>
    <li>
    <font color="#dd0000">$c</font> = __NAMESPACE__ . <font color="#0000ff">'\\MyClass'</font>;  </li>
    <li class="alt">
    <font color="#dd0000">$m</font> = <strong><font color="#006699">new</font></strong> <font color="#dd0000">$c</font>;  </li>
    <li>echo <font color="#dd0000">$m</font>->WhoAmI(); <font color="#008200">// outputs: App\Lib1\MyClass::WhoAmI </font> </li>
    <li class="alt">?>  </li>
    </ol>
    Copy after login

    namespace关键字

    namespace关键字可以用于明确引用一个当前命名空间或子命名空间中的项目,它等价于类中的self命名空间:

    <ol class="dp-c">
    <li class="alt">namespace App\Lib1;  </li>
    <li class="alt"> </li>
    <li>
    <strong><font color="#006699">class</font></strong> MyClass {  </li>
    <li class="alt"> <strong><font color="#006699">public</font></strong> <strong><font color="#006699">function</font></strong> WhoAmI() {  </li>
    <li>
    <strong><font color="#006699">return</font></strong> <strong><font color="#006699">__METHOD__</font></strong>;  </li>
    <li class="alt"> }  </li>
    <li>}  </li>
    <li class="alt"> </li>
    <li>
    <font color="#dd0000">$m</font> = <strong><font color="#006699">new</font></strong> namespace\MyClass;  </li>
    <li class="alt">echo <font color="#dd0000">$m</font>->WhoAmI(); <font color="#008200">// outputs: App\Lib1\MyClass::WhoAmI </font> </li>
    <li>?>  </li>
    </ol>
    Copy after login

    自动载入命名空间类

    PHP 5中最省时省力的特性是自动载入,在全局(非命名空间)PHP代码中,可以写一个标准自动载入函数:

    <ol class="dp-c">
    <li class="alt">
    <font color="#dd0000">$obj</font>= <strong><font color="#006699">new</font></strong> MyClass1(); <font color="#008200">// classes/MyClass1.php is auto-loaded </font> </li>
    <li class="alt">
    <font color="#dd0000">$obj</font>= <strong><font color="#006699">new</font></strong> MyClass2(); <font color="#008200">// classes/MyClass2.php is auto-loaded </font> </li>
    <li> </li>
    <li class="alt">
    <font color="#008200">// autoload function </font> </li>
    <li>
    <strong><font color="#006699">function</font></strong> __autoload(<font color="#dd0000">$class_name</font>) {  </li>
    <li class="alt"> <strong><font color="#006699">require_once</font></strong>(<font color="#0000ff">"classes/$class_name.php"</font>);  </li>
    <li>}  </li>
    <li class="alt">?>  </li>
    </ol>
    Copy after login

    在PHP 5.3中,你可以创建一个命名空间类的实例,在这种情况下,完全限定命名空间和类名传递给__autoload函数,例如,$class_name的值可 能是App\Lib1\MyClass。你可以在相同的文件夹下放置所有的PHP类文件,从字符串中提取命名空间,但那样会导致文件名冲突。

    另外,你的类文件层次结构会按照命名空间的结构重新组织,例如,MyClass.php文件可以创建在/classes/App/Lib1文件夹下:

    /classes/App/Lib1/MyClass.php

    <ol class="dp-c">
    <li class="alt">namespace App\Lib1;  </li>
    <li class="alt"> </li>
    <li>
    <strong><font color="#006699">class</font></strong> MyClass {  </li>
    <li class="alt"> <strong><font color="#006699">public</font></strong> <strong><font color="#006699">function</font></strong> WhoAmI() {  </li>
    <li>
    <strong><font color="#006699">return</font></strong> <strong><font color="#006699">__METHOD__</font></strong>;  </li>
    <li class="alt"> }  </li>
    <li>}  </li>
    <li class="alt">?>  </li>
    </ol>
    Copy after login

    在根文件夹下的文件就使用下面的代码了:

    myapp.php

    <ol class="dp-c">
    <li class="alt">
    <strong><font color="#006699">use</font></strong> App\Lib1\MyClass <strong><font color="#006699">as</font></strong> MC;  </li>
    <li class="alt"> </li>
    <li>
    <font color="#dd0000">$obj</font> = <strong><font color="#006699">new</font></strong> MC();  </li>
    <li class="alt">echo <font color="#dd0000">$obj</font>->WhoAmI();  </li>
    <li> </li>
    <li class="alt">
    <font color="#008200">// autoload function </font> </li>
    <li>
    <strong><font color="#006699">function</font></strong> __autoload(<font color="#dd0000">$class</font>) {  </li>
    <li class="alt"> <font color="#008200">// convert namespace to full file path </font> </li>
    <li> <font color="#dd0000">$class</font> = <font color="#0000ff">'classes/'</font> . str_replace(<font color="#0000ff">'\\', '</font>/<font color="#0000ff">', $class) . '</font>.php';  </li>
    <li class="alt"> <strong><font color="#006699">require_once</font></strong>(<font color="#dd0000">$class</font>);  </li>
    <li>}  </li>
    <li class="alt">?>  </li>
    </ol>
    Copy after login

    解释:

    1.类App\Lib1\MyClass的别名是MC;

    2. new MC( )在编译时被翻译成new App\Lib1\MyClass( );

    3.字符串App\Lib1\MyClass被传递给__autoload函数,使用文件路径正斜线替换所有命名空间中的反斜线,然后修改字符串,classes\App\Lib1\MyClass.php文件被自动载入;

    总结

    有关PHP命名空间的使用就介绍到这里,希望您能够对PHP的命名空间有一个新的认识,并希望你能在新项目中真正使用命名空间。

    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

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    1 months ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

    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

    How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

    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

    How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

    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

    7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

    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

    Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

    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,

    PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

    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

    Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

    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 PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

    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.

    See all articles