PHP namespace rules parsing and advanced features

Source: Internet
Author: User
Tags autoload

Recent releases of PHP5The most important new feature in. 3 is the addition of namespaces. This article describes some of the terminology of the PHP namespace, its parsing rules, and the application of some advanced features, in the hope of helping readers to really use namespaces in their projects. Here we introduce the use of the PHP namespace and the namespace keyword, in this article we will describe the use command and how php resolves the name of the namespace. For the sake of comparison, I defined two almost the same block of code, with only a different name for the namespace. <?PHP//Application Library 1namespaceAPP\LIB1; ConstMyconst ='App\lib1\myconst'; function MyFunction () {return__function__; }  classMyClass {Staticfunction WhoAmI () {Eturn __method__; }  }  ?>lib2.php<?PHP//Application Library 2namespaceApp\lib2; ConstMyconst ='App\lib2\myconst'; function MyFunction () {return__function__; }   classMyClass {Staticfunction WhoAmI () {Eturn __method__; }  }  ?>before you begin, understand several PHP namespace-related terms. Fully qualified name (Fully-qualified name) any PHP code can reference the fully qualified name, which is an identifier that begins with a namespace backslash, such as \app\lib1\myconst,\app\lib2\myfunction (). The fully qualified name is not ambiguous, the beginning of the backslash and the role of the file path is somewhat similar, it represents the "root" global space, if we implement a different MyFunction in the global Space (), you can use \myfunction () Call it from lib1.php or lib2.php. Fully qualified names are useful for one-time function calls or object initialization, but when you generate a large number of calls they are of no practical value, as we will see in the following discussion that PHP offers other options to relieve us of the hassle of typing in namespaces. The qualified name (qualified name) has at least one identifier for the namespace delimiter, such as lib1\myfunction (). The unqualified name (Unqualified name) has no identifier for the namespace delimiter, such as MyFunction (). Work within the same namespace think carefully the following code: myapp1.php<?PHPnamespaceAPP\LIB1; Require_once ('lib1.php'); Require_once ('lib2.php'); Header ('Content-type:text/plain'); Echo Myconst. "\ n"; Echo MyFunction (). "\ n"; Echo Myclass::whoami (). "\ n"; ?>even if we include both the lib1.php and the Lib2.php,myconst,myfunction and the MyClass identifiers can only be referenced in lib1.php, this is because the myapp1.php code is within the same APP\LIB1 namespace. Execution Result: App\lib1\myconst app\lib1\myfunction App\lib1\myclass::whoami namespace import you can import namespaces using the use operator, such as: myapp2.php<?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"; ?>any number of use statements can be defined, or separated into separate namespaces using commas, in which case we have imported the App\lib2 namespace, but we still cannot refer directly to Myconst,myfunction and MyClass, Because our code is still in the global space, but if we add the "lib2\" prefix, they become qualified names, PHP will search the imported namespaces until a match is found. Execution result: The App\lib2\myconst app\lib2\myfunction App\lib2\myclass::whoami namespace alias namespace alias is probably the most useful idea, and aliases allow us to reference very long namespaces with shorter names. myapp3.php<?PHP use APP\LIB1 asL; Use App\lib2\myclass asOBJ; Header ('Content-type:text/plain'); Require_once ('lib1.php'); Require_once ('lib2.php'); Echo L\myconst. "\ n"; Echo L\myfunction (). "\ n"; Echo L\myclass::whoami (). "\ n"; Echo Obj::whoami (). "\ n"; ?>The first Use statement defines APP\LIB1 as "L", and any qualified name using "L" will be translated to "APP\LIB1" at compile time, so we can refer to L\myconst and l\myfunction instead of fully qualified names. The second use statement defines "obj" as an alias for the MyClass class in the App\lib2\ namespace, which is only suitable for classes, not constants and functions, and now we can run static methods using new obj () or as above.  Execution Result: App\lib1\myconst app\lib1\myfunction App\lib1\myclass::whoami App\lib2\myclass::whoami PHP name resolution rules PHP identifier names are resolved using the following namespace rules, please refer to the PHP user manual for more detailed information:1. Call a fully qualified function, class, or constant at compile time;2The unqualified name and qualified name are translated according to the import rules, for example, if a\b\c is imported as C, the call C\d\e () will be translated into a\b\c\d\e ();3within the PHP namespace, all qualified names have not been converted according to the import rules, for example, if C\d\e () is called in the namespace a\b, then it will be translated into a\b\c\d\e ();4The unqualified class name is converted according to the current import rule, replacing the imported short name with the full name, for example, if class C is imported as X in the namespace a\b, then New X () is translated to New a\b\c ();5In the namespace, non-qualifying function calls are resolved at run time, for example, if MyFunction () is called in the namespace a\b, PHP first looks for the function \a\b\myfunction (), if it is not found, and then looks in the global space \ MyFunction ();6call unqualified or qualified class names are parsed at run time, for example, if we call New C () in the namespace a\b, PHP will look for class a\b\c, and if not found, PHP will attempt to automatically load a\b\c. PHP namespace advanced features Let's take a look at some of the advanced features of the PHP namespace. __NAMESPACE__ constant __namespace__ is a PHP string that always returns the name of the current namespace, which is an empty string in the global space. <?PHPnamespaceAPP\LIB1; Echo __namespace__; //OUTPUTS:APP\LIB1?>This value is useful when debugging, and it can also be generated by dynamically generating a fully qualified class name, such as:<?PHPnamespaceAPP\LIB1; classMyClass { Publicfunction WhoAmI () {return__method__; }} $c= __namespace__.'\\MyClass'; $m=New$c; Echo $m->whoami ();//Outputs:app\lib1\myclass::whoami?>The namespace keyword namespace keyword can be used to explicitly reference an item in a current namespace or child namespace, which is equivalent to the self namespace in a class:<?PHPnamespaceAPP\LIB1; classMyClass { Publicfunction WhoAmI () {return__method__; }} $m=New namespace\myclass; Echo $m->whoami ();//Outputs:app\lib1\myclass::whoami?>automatically load namespace class The most time-saving feature in PHP 5 is auto-loading, and in the global (non-namespace) PHP code, you can write a standard auto-load function:<?PHP $obj=NewMyClass1 ();//classes/myclass1.php is auto-loaded$obj =NewMyClass2 ();//classes/myclass2.php is auto-loaded//autoload functionfunction __autoload ($class _name) {require_once ("classes/$class _name.php"); }  ?>in PHP5. 3, you can create an instance of a namespace class, in which case the fully qualified namespace and class name are passed to the __autoload function, for example, the value of $class _name may be app\lib1\myclass. You can place all the PHP class files under the same folder, extracting the namespaces from the string, but that can cause file name collisions. In addition, your class file hierarchy is re-organized according to the structure of the namespace, for example, the myclass.php file can be created in/classes/app/under the Lib1 folder:/classes/app/lib1/myclass.php<?PHPnamespaceAPP\LIB1; classMyClass { Publicfunction WhoAmI () {return__method__; }  }  ?>The file under the root folder uses the following code: myapp.php<?PHP use App\lib1\myclass asMC; $obj=NewMC (); Echo $obj-WhoAmI (); //autoload functionFunction __autoload ($class) {   //convert namespace to full file path$class='classes/'. Str_replace ('\\','/', $class) .'. PHP'; Require_once ($class); }  ?>Explanation:1the alias of the. Class App\lib1\myclass is MC;2.NewMC () is translated into new App\lib1\myclass () at compile time;3The . String App\lib1\myclass is passed to the __autoload function, replacing the backslash in all namespaces with a file-path forward slash, and then modifying the string, classes\app\lib1\ The myclass.php file is automatically loaded, summarizing the use of the PHP namespace is introduced here, I hope you can have a new understanding of the PHP namespace, and I hope you can really use the namespace in the new project. 

PHP namespace rules parsing and advanced features

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.