PHP namespace rule parsing and advanced features

Source: Internet
Author: User
Tags aliases execution header new features php class php and php code reference
One of the most important new features of PHP 5.3 that has recently been released is the addition of namespaces. This article describes some of the terms of the PHP namespace, its parsing rules, and the application of some advanced features, in the hope that it will help readers actually use namespaces in their projects.

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

For ease of comparison, I've defined two almost identical blocks of code, only the names of namespaces are different.

    1. < PHP
    2. //Application library 1
    3. namespace APP\LIB1;
    4. Const Myconst = ' App\lib1\myconst ';
    5. function MyFunction () {
    6. return __function__;
    7. }
    8. class MyClass {
    9. Static function WhoAmI () {
    10. Eturn __method__;
    11. }
    12. }
    13. ?>

lib2.php

  1. < PHP
  2. //Application Library 2
  3. namespace App\lib2;
  4. Const Myconst = ' App\lib2\myconst ';
  5. function MyFunction () {
  6. return __function__;
  7. }
  8. class MyClass {
  9. Static function WhoAmI () {
  10. Eturn __method__;
  11. }
  12. }
  13. ?>

Before you begin, understand several PHP namespace-related terms.

Fully qualified name (fully-qualified name)

Any PHP code can refer to a 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 file path function is somewhat similar, it represents the "root" global space, if we implement a different myfunction in the global Space (), you can use the \myfunction () Call it from lib1.php or lib2.php.

Fully qualified names are useful for one-off function calls or object initialization, but they have no practical value when you produce a large number of calls, as we will see in the discussion below that PHP offers other options to remove the annoyance of typing in namespaces.

Qualified names (qualified name)

An identifier for at least one namespace delimiter, such as lib1\myfunction ().

Unqualified names (unqualified name)

An identifier that does not have a namespace delimiter, such as MyFunction ().

Work within the same namespace

Think carefully about the following code:

myapp1.php

     
     
     
  1. < PHP
  2. namespace APP\LIB1;
  3. require_once (' lib1.php ');
  4. require_once (' lib2.php ');
  5. Header (' Content-type:text/plain ');
  6. Echo Myconst. "\ n";
  7. Echo MyFunction (). "\ n";
  8. Echo Myclass::whoami (). "\ n";
  9. ?>

Even if we include the lib1.php and Lib2.php,myconst,myfunction and MyClass identifiers can only be referenced in lib1.php, this is because the myapp1.php code is in the same APP\LIB1 namespace.

Execution results:

    1. App\lib1\myconst
    2. App\lib1\myfunction
    3. App\lib1\myclass::whoami

Namespace Import

You can import namespaces using the use operator, such as:

myapp2.php

    1. < PHP
    2. Use APP\LIB2;
    3. require_once (' lib1.php ');
    4. require_once (' lib2.php ');
    5. Header (' Content-type:text/plain ');
    6. Echo Lib2\myconst. "\ n";
    7. Echo Lib2\myfunction (). "\ n";
    8. Echo Lib2\myclass::whoami (). "\ n";
    9. ?>

You can define any number of use statements, or separate namespaces with commas, in which we import the App\lib2 namespace, but we still can't refer to myconst,myfunction and MyClass directly, because our code is still in global space, But if we add the "lib2\" prefix, they become qualified names, and PHP searches for the imported namespaces until a match is found.

Execution results:

    1. App\lib2\myconst
    2. App\lib2\myfunction
    3. App\lib2\myclass::whoami

Name Space Alias

Namespace aliases may be the most useful idea, and aliases allow us to refer to long namespaces with shorter names.

myapp3.php

  1. < PHP
  2. Use APP\LIB1 as L;
  3. Use App\lib2\myclass as OBJ;
  4. Header (' Content-type:text/plain ');
  5. require_once (' lib1.php ');
  6. require_once (' lib2.php ');
  7. Echo L\myconst. "\ n";
  8. Echo L\myfunction (). "\ n";
  9. Echo L\myclass::whoami (). "\ n";
  10. Echo Obj::whoami (). "\ n";
  11. ?>

The first Use statement defines APP\LIB1 as "L", and any qualified name that uses "L" is translated to "APP\LIB1" at compile time, so we can reference l\myconst and l\myfunction rather than fully qualified names.

The second use statement defines "obj" as an alias to the MyClass class in the App\lib2\ namespace, which is only suitable for classes and cannot be used for constants and functions, and we now have the option of using new obj () or running static methods like the above.

Execution results:

    1. App\lib1\myconst
    2. App\lib1\myfunction
    3. App\lib1\myclass::whoami
    4. App\lib2\myclass::whoami

PHP Naming resolution rules

The PHP identifier name is parsed using the following namespace rules, please refer to the PHP user's manual for more detailed information:

1. Call a fully qualified function, class, or constant at compile time;

2. Unqualified names and qualified names are translated according to the import rules, for example, if a\b\c is imported as C, the call to C\d\e () is translated to A\b\c\d\e ();

3. Within the PHP namespace, all qualified names have not been converted according to the import rule, for example, if C\d\e () is invoked in the namespace a\b, it is translated to a\b\c\d\e ();

4. Unqualified class names are 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 ();

5. Non-qualifying function calls in namespaces are parsed at run time, for example, if MyFunction () is invoked in the namespace a\b, PHP first looks for the function \a\b\myfunction (), if it is not found, then finds \myfunction in the global space ( );

6. Calling the unqualified or qualified class name is parsed at run time, for example, if we call New C () in the namespace a\b, PHP will look for the class a\b\c, and if not, PHP will try to load a\b\c automatically.


PHP namespace Advanced Features

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

__namespace__ Constants

__namespace__ is a PHP string that always returns the name of the current namespace, which is an empty string in the global space.

     
     
     
  1. < PHP
  2. namespace APP\LIB1;
  3. Echo __namespace__;
  4. ?>

This value is useful when debugging, and it can also be generated by dynamically generating a fully qualified class name, such as:

     
     
    1. < ?php  
    2. namespace app\lib1;  
    3.  
    4. class  myclass { 
    5.   public   function  whoami ()  { 
    6. return   __method__ ;  
    7.    
    8. }  
    9.  
    10. $c  =& Nbsp;__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 an item in the current namespace or child namespace, which is equivalent to the self namespace in the class:

 
     
     
  1. < ?php  
  2. namespace  App\Lib1;  
  3.  
  4. class  myclass { 
  5.   public   function< /font>  whoami ()  { 
  6. return  < Strong>__method__ ;  
  7.    
  8. }  
  9.  
  10. $m  =  new  namespace\MyClass;  
  11. echo  $m ->whoami ()  //  Outputs: app\lib1\myclass::whoami  
  12. ?>  

Automatically load namespace classes

The most time-saving and time-saving feature of PHP 5 is automatic loading, in the Global (namespace) PHP code, you can write a standard automatic loading function:

   
     
     
  1. < PHP
  2. $obj= new MyClass1 ();
  3. $obj= new MyClass2 ();
  4. function __autoload ($class _name) {
  5. require_once ("classes/$class _name.php");
  6. }
  7. ?>

In PHP 5.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 the $class _name may be app\lib1\myclass. You can place all the PHP class files in the same folder and extract the namespaces from the string, but that can cause file name collisions.

In addition, your class file hierarchy is organized according to the namespace structure, for example, myclass.php files can be created under the/CLASSES/APP/LIB1 folder:

/classes/app/lib1/myclass.php

     
     
     
  1. < PHP
  2. namespace APP\LIB1;
  3. class MyClass {
  4. Public function WhoAmI () {
  5. return __method__;
  6. }
  7. }
  8. ?>

The file under the root folder uses the following code:

myapp.php

     
     
  1. < PHP
  2. Use App\lib1\myclass as MC;
  3. $obj = new MC ();
  4. echo $obj->whoami ();
  5. //AutoLoad function
  6. function __autoload ($class) {
  7. //Convert namespace to full file path
  8. $class = ' classes/' . Str_replace (' \ \', '/', $class). '. php ';
  9. require_once ($class);
  10. }
  11. ?>

Explain:

1. The alias of Class App\lib1\myclass is MC;

2. New MC () is translated into new App\lib1\myclass () at compile time;

3. The string App\lib1\myclass is passed to the __autoload function, replaces the backslash in all namespaces with the file path forward slash, and then modifies the string, classes\app\lib1\myclass.php the file is automatically loaded;

Summarize

For the use of the PHP namespace here, I hope you have a new understanding of the PHP namespace and that you will be able to really use namespaces in your 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.