The purpose of the PHP namespaces and the namespace keyword

Source: Internet
Author: User
Tags autoload aliases php class

< PHP//Application library 1 namespace AppLib1;   Const MYCONST = ' applib1myconst ';  function MyFunction () {return __function__;   Class MyClass {static function WhoAmI () {Eturn __method__; }}?> lib2.php

< PHP//Application library 2 namespace AppLib2;   Const MYCONST = ' applib2myconst ';  function MyFunction () {return __function__;   Class MyClass {static function WhoAmI () {Eturn __method__; ?> to understand several PHP namespace-related terms before starting.

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 applib1myconst,applib2myfunction ().

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 lib1myfunction ().

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

< PHP namespace APPLIB1;  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 lib1.php and lib2.php,myconst,myfunction and MyClass identifiers can only be referenced in lib1.php because the myapp1.php code is in the same APPLIB1 namespace.

Execution results:

Applib1myconst applib1myfunction Applib1myclass::whoami Namespace Import

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

myapp2.php

< PHP use APPLIB2;  Require_once (' lib1.php ');   Require_once (' lib2.php ');  Header (' Content-type:text/plain '); Echo Lib2myconst.  "N"; Echo Lib2myfunction ().  "N"; Echo Lib2myclass::whoami ().  "N"; ?> can define any number of use statements, or separate namespaces with commas, in this case we import the AppLib2 namespace, but we still can't directly reference myconst,myfunction and MyClass, Because our code is still in global space, if we add the "Lib2" prefix, they become qualified names, and PHP will search for the imported namespaces until a match is found.

Execution results:

Applib2myconst Applib2myfunction Applib2myclass::whoami namespace alias

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

myapp3.php

< PHP use APPLIB1 as L;   Use Applib2myclass as OBJ;  Header (' Content-type:text/plain ');  Require_once (' lib1.php ');   Require_once (' lib2.php '); Echo Lmyconst.  "N"; Echo Lmyfunction ().  "N"; Echo Lmyclass::whoami ().  "N"; Echo Obj::whoami ().  "N"; ?> The first Use statement defines APPLIB1 as "L", any qualified name that uses "L" is translated to "APPLIB1" at compile time, so we can reference lmyconst and lmyfunction instead of fully qualifying the name.

The second use statement defines "obj" as an alias to the MyClass class in the AppLib2 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:

Applib1myconst applib1myfunction Applib1myclass::whoami Applib2myclass::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 and qualified names are translated according to the import rules, for example, if ABC is imported as C, the call to CDE () is translated to ABCDE ();

3. Within the PHP namespace, all qualified names have not been converted according to the import rule, for example, if the CDE () is invoked in namespace AB, it is translated to ABCDE ();

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 namespace AB, then New X () is translated to New ABC ();

5. Non-qualifying function calls in namespaces are parsed at run time, for example, if MyFunction () is invoked in namespace AB, PHP first looks for function abmyfunction (), and if not, then looks up MyFunction () in the global space;

6. Calling unqualified or qualified class names is parsed at run time, for example, if we call New C () in namespace AB, PHP will look for class ABC, and if not, PHP will try to automatically load ABC
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.

< PHP namespace APPLIB1; Echo __namespace__; OUTPUTS:APPLIB1?> This value is useful when debugging, and it can also be generated by dynamically generating a fully qualified class name, such as:

< PHP namespace APPLIB1;   Class MyClass {public Function WhoAmI () {return __method__; }} $c = __namespace__.  ' \myclass ';  $m = new $c; echo $m->whoami (); Outputs:applib1myclass::whoami?> 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:

< PHP namespace APPLIB1;   Class MyClass {public Function WhoAmI () {return __method__;  }} $m = new Namespacemyclass; echo $m->whoami (); Outputs:applib1myclass::whoami?> automatically load namespace class

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:

< php $obj = new MyClass1 (); classes/myclass1.php is auto-loaded $obj = new MyClass2 (); Classes/myclass2.php is auto-loaded//autoload function function __autoload ($class _name) {require_once ("classes/  $class _name.php "); ?> 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 applib1myclass. 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

< PHP namespace APPLIB1;   Class MyClass {public Function WhoAmI () {return __method__; The following code is used to?> files under the root folder:

myapp.php

< PHP use Applib1myclass as MC;  $obj = new MC ();   echo $obj->whoami (); autoload function function __autoload ($class) {//Convert namespace to full file path $class = ' classes/'. Str_r Eplace (' \ ', '/', $class).   '. php ';  Require_once ($class); ?> explains:

1. The alias of Class Applib1myclass is MC;

2. New MC () is translated into new Applib1myclass () at compile time;

3. The string Applib1myclass is passed to the __autoload function, replaces the backslash in all namespaces with the file path forward slash, and then modifies the string, classesapplib1myclass.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.