New namespace rule parsing and advanced function-PHP Tutorial

Source: Internet
Author: User
New namespace rule parsing and advanced functions in PHP5.3. In PHP5.3, the most important new feature is the addition of namespaces. This article introduces some terms of the PHP namespace, its parsing rules, and some advanced features of the application recently released in PHP 5.3. The most important new feature is the addition of the namespace. 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. 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 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. ?>

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. 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 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. 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 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. // autoload function
  5. function __autoload($class_name) {
  6. require_once("classes/$class_name.php");
  7. }
  8. ?>

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. class MyClass {
  4. public function WhoAmI() {
  5. return __METHOD__;
  6. }
  7. }
  8. ?>

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

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

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.

In lifecycle 5.3, the most important new feature is the addition of namespaces. This article introduces some terms of the PHP namespace, its parsing rules, and some advanced functions...

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.