New namespace rule parsing and advanced functions in PHP 5.3

Source: Internet
Author: User

One of the most important new features of PHP 5.3 released recently is the addition of namespaces. This article introduces some terms, parsing rules, and application of some advanced functions of PHP namespaces, hoping to help readers use namespaces in projects.

Here we will introduce the usage of the PHP namespace and the namespace keyword. In this article, we will introduce the use of the use command and how PHP resolves the namespace name.

To facilitate the comparison, I have defined two almost identical code blocks, only with different namespaces.

  1. <? Php
  2. // Application library 1 
  3. Namespace App \ Lib1;
  4. ConstMYCONST ='App \ Lib1 \ myconst';
  5. FunctionMyFunction (){
  6.  Return _ FUNCTION __;
  7. }
  8. ClassMyClass {
  9.  Static FunctionWhoAmI (){
  10. Eturn_ METHOD __;
  11. }
  12. }
  13. ?>

Lib2.php

  1. <? Php
  2. // Application library 2 
  3. Namespace App \ Lib2;
  4. ConstMYCONST ='App \ Lib2 \ myconst';
  5. FunctionMyFunction (){
  6.  Return _ FUNCTION __;
  7. }
  8. ClassMyClass {
  9.  Static FunctionWhoAmI (){
  10. Eturn_ METHOD __;
  11. }
  12. }
  13. ?>

Before you start, you must understand several terms related to PHP namespaces.

◆ Fully qualified name (Fully-qualified name)

Any PHP code can reference a fully qualified name. It is an identifier starting with a namespace backslash, for example, \ App \ Lib1 \ MYCONST, \ App \ Lib2 \ MyFunction.

The fully qualified name is unambiguous. The backslash at the beginning is similar to the file path. It indicates the global space of "root, if we implement a different MyFunction () in the global space, we can use \ MyFunction () to call it from lib1.php or lib2.php.

Fully qualified names are very useful for one-time function calls or object initialization, but they do not have practical value when you generate a large number of calls. As we will see in the following discussion, PHP provides other options to ease typing in namespaces.

◆ Qualified name)

There must be at least one namespace separator identifier, such as Lib1 \ MyFunction ().

◆ Unqualified name)

There is no namespace separator identifier, such as MyFunction ().

Work in the same namespace

Think carefully about the following code:

Myapp1.php

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

Even if we include both lib1.php and lib2.php, MYCONST, MyFunction, and MyClass identifiers, we can only reference them in lib1.php because the code of myapp1.php is in the same App \ Lib1 namespace.

Execution result:

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

Namespace Import

You can use the use operator to import namespaces, for example:

Myapp2.php

 <? Php
  1. UseApp \ Lib2;
  2. Require_once('Lib1. php');
  3. Require_once('Lib2. php');
  4. Header ('Content-type: text/plain');
  5. EchoLib2 \ MYCONST."\ N";
  6. EchoLib2 \ MyFunction ()."\ N";
  7. EchoLib2 \ MyClass: WhoAmI ()."\ N";
  8. ?>
 

You can define any number of use statements or use commas to separate them into independent namespaces. In this example, we imported the App \ Lib2 namespace, but we still cannot directly reference MYCONST, myFunction and MyClass, because our code is still in the global space, but if we add the "Lib2 \" prefix, they will become qualified names, PHP searches for the imported namespace until a match is found.

Execution result:

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

Namespace alias

A namespace alias may be the most useful concept. It allows us to reference a long namespace with a short name.

Myapp3.php

  1. <? Php
  2. UseApp \ Lib1AsL;
  3. UseApp \ Lib2 \ MyClassAsObj;
  4. Header ('Content-type: text/plain');
  5. Require_once('Lib1. php');
  6. Require_once('Lib2. php');
  7. EchoL \ MYCONST."\ N";
  8. EchoL \ MyFunction ()."\ N";
  9. EchoL \ MyClass: WhoAmI ()."\ N";
  10. EchoObj: WhoAmI ()."\ N";
  11. ?>

The first use statement defines App \ Lib1 as "L". Any qualified name using "L" will be translated into "App \ Lib1" during compilation ", therefore, we can reference L \ MYCONST and L \ MyFunction instead of fully qualified names.

The second use statement defines "obj" as the alias of the MyClass class in the App \ Lib2 \ namespace. This method is only applicable to classes and cannot be used for constants and functions, now we can use new Obj () or run the static method as above.

Execution result:

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

PHP naming rules

The PHP identifier name is parsed using the following namespace rules. For more information, see the PHP user manual:

1. Call fully qualified functions, classes, or constants during compilation;

2. for example, if A \ B \ C is imported as C, call C \ D \ e () it will be translated into A \ B \ C \ D \ e ();

3. in the PHP namespace, all qualified names have not been converted according to the import rules. For example, if C \ D \ e () is called in namespace A \ B (), it will be translated into A \ B \ C \ D \ e ();

4. the unqualified class name is converted according to the current import rule, and the short name of the import is replaced by the full name. For example, if Class C is imported as X in namespace A \ B, then new X () will be translated into new A \ B \ C ();

5. non-limited function calls in A namespace are parsed at runtime. For example, if MyFunction () is called in namespace A \ B, PHP first searches for the function \ A \ B \ MyFunction (). If not, it searches for \ MyFunction () in the global space ();

6. the call of an unqualified or qualified class name is parsed at runtime. For example, if we call new C () in namespace A \ B (), PHP will search for Class A \ B \ C. If it cannot be found, PHP will try to automatically load A \ B \ C.


PHP namespace advanced features

Next, let's take a look at some advanced features of the PHP namespace.

_ NAMESPACE _ constant

_ NAMESPACE _ is a PHP string that always returns the name of the current NAMESPACE. It is an empty string in the global space.

      
     
  1. < ?php  
  2. namespace App\Lib1;  
  3. echo __NAMESPACE__; // outputs: App\Lib1  
  4. ?>  
  5.  

This value is very useful during debugging. It can also dynamically generate a fully qualified class name, for example:

      
     
  1. < ?php  
  2. namespace App\Lib1;  
  3.  
  4. class MyClass {  
  5.  public function WhoAmI() {  
  6. return __METHOD__;  
  7.  }  
  8. }  
  9.  
  10. $c = __NAMESPACE__ . '\\MyClass';  
  11. $m = new $c;  
  12. echo $m->WhoAmI(); // outputs: App\Lib1\MyClass::WhoAmI  
  13. ?>  

Namespace keyword

The namespace keyword can be used to explicitly reference a project in the current namespace or sub-namespace. It is equivalent to the self namespace in the class:

      
     
  1. < ?php  
  2. namespace App\Lib1;  
  3.  
  4. class MyClass {  
  5.  public function WhoAmI() {  
  6. return __METHOD__;  
  7.  }  
  8. }  
  9.  
  10. $m = new namespace\MyClass;  
  11. echo $m->WhoAmI(); // outputs: App\Lib1\MyClass::WhoAmI  
  12. ?>  

Automatically load the namespace class

The most time-saving feature in PHP 5 is automatic loading. In the global (non-namespace) PHP code, you can write a standard automatic loading function:

      
     
  1. < ?php  
  2. $obj= new MyClass1(); // classes/MyClass1.php is auto-loaded  
  3. $obj= new MyClass2(); // classes/MyClass2.php is auto-loaded  
  4.  
  5. // autoload function  
  6. function __autoload($class_name) {  
  7.  require_once("classes/$class_name.php");  
  8. }  
  9. ?>  

In PHP 5.3, you can create a namespace class instance. In this case, the namespace and class name are completely limited and passed to the _ autoload function. For example, the value of $ class_name can be App \ Lib1 \ MyClass. You can place all PHP class files in the same folder and extract the namespace from the string, but this will cause File Name Conflict.

In addition, your class File hierarchy will be reorganized according to the namespace structure. For example, the MyClass. php file can be created in the/classes/App/Lib1 Folder:

/Classes/App/Lib1/MyClass. php

      
     
  1. < ?php  
  2. namespace App\Lib1;  
  3.  
  4. class MyClass {  
  5.  public function WhoAmI() {  
  6. return __METHOD__;  
  7.  }  
  8. }  
  9. ?>  

The following code is used for files in the root folder:

Myapp. php

      
     
  1. < ?php  
  2. use App\Lib1\MyClass as MC;  
  3.  
  4. $obj = new MC();  
  5. echo $obj->WhoAmI();  
  6.  
  7. // autoload function  
  8. function __autoload($class) {  
  9.  // convert namespace to full file path  
  10.  $class = 'classes/' . str_replace('\\', '/', $class) . '.php';  
  11.  require_once($class);  
  12. }  
  13. ?>  

Explanation:

1. the alias of the class App \ Lib1 \ MyClass is MC;

2. new MC () is translated into new App \ Lib1 \ MyClass () during compilation ();

3. the string App \ Lib1 \ MyClass is passed to the _ autoload function. Use the file path forward slash to replace the backslash in all namespaces, and then modify the string, classes \ App \ Lib1 \ MyClass. PHP files are automatically loaded;

Summary

This section describes how to use the PHP namespace. I hope you can have a new understanding of the PHP namespace and hope you can actually use the namespace in the new project.

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.