PHP 5.3 New Feature namespace rule parsing and advanced features _php tutorial

Source: Internet
Author: User
Tags autoload php class vars
One of the most important new features of PHP 5.3 that has been released recently 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.

  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 reference 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 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.

Qualified name (qualified name)

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

Unqualified names (Unqualified name)

An identifier without a namespace delimiter, such as MyFunction ().

Working 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 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:

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

Namespace Import

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

myapp2.php

< PHP
    1. use app\lib2;
    2. require_once ( ' lib1.php ' );
    3. require_once ( ' lib2.php ' );
    4. header ( "content-type:text/ Plain ' );
    5. echo lib2\myconst. "\ n" ;
    6. echo lib2\myfunction (). "\ n" ;
    7. echo Lib2\myclass::whoami (). "\ n" ;
    8. ?>

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, and PHP will search for the imported namespaces until a match is found.

Execution Result:

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

namespace aliases

Namespace aliases are probably the most useful idea, and aliases allow us to reference very 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 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:

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

PHP Naming 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;

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

3. Within 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, it will be translated into a\b\c\d\e ();

4. The 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 ();

5. Non-qualifying function calls in the namespace 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 (), and if it is not found, then finds \myfunction in the global space ( );

6. Call 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

Now 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
  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. class MyClass {
  4. public Function WhoAmI () {
  5. return __method__;
  6. }
  7. }
  8. $c = __namespace__. ' \\MyClass ' ;
  9. $m = New $c;
  10. Echo $m->whoami (); //Outputs:app\lib1\myclass::whoami
  11. ?>

namespace keywords

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. class MyClass {
  4. public Function WhoAmI () {
  5. return __method__;
  6. }
  7. }
  8. $m = New Namespace\myclass;
  9. Echo $m->whoami (); //Outputs:app\lib1\myclass::whoami
  10. ?>

Automatically load namespace classes

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:

      
     
  1. < PHP
  2. $obj = New MyClass1 (); //classes/myclass1.php is auto-loaded
  3. $obj = New MyClass2 (); //classes/myclass2.php is auto-loaded
  4. //AutoLoad function
  5. function __autoload ($class _name) {
  6. require_once("classes/$class _name.php");
  7. }
  8. ?>

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 $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 will be re-organized according to the structure of the namespace, for example, the myclass.php file 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, replacing the backslash in all namespaces with a file-path forward slash, and then modifying the string, classes\app\lib1\myclass.php the file is automatically loaded;

Summarize

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.

http://www.bkjia.com/PHPjc/321331.html www.bkjia.com true http://www.bkjia.com/PHPjc/321331.html techarticle one of the most important new features of PHP 5.3 that has been released recently 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 ...

  • Related Article

    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.