PHP namespace details-PHP source code

Source: Internet
Author: User
This article mainly introduces the namespace in PHP and explains the namespace) concept, namespace being used, namespace defining, sub-namespace, calling code from namespace, etc, for more information about namespaces in PHP, see the following article) for more information, see

Overview

PHP's support for namespaces has gone through a difficult journey. Fortunately, PHP introduced namespaces from 5.3. Since PHP introduced namespace, the applicable structure of PHP code has also been greatly improved. Many programming languages have long had the concept of namespaces. compared with other languages, PHP's support for namespaces is a little late. In any case, the introduction of each new feature has a purpose. Like other languages, the introduction of namespaces in PHP is mainly used to solve name conflicts.

Namespace concept

The code is as follows:

When using a namespace name in a string, do not forget to escape \


You can think of a namespace as a drawer. you can put pencils, rulers, and A4 paper in the drawer. these are your own private items. Under your drawer is someone else's drawer, others can also put the same item in the drawer. In order not to take the wrong item, you decide to add a label on your drawer so that you can clearly see who the item belongs.

Previously, developers must add underscores to classes, functions, and constants to separate their code from other code libraries. This is equivalent to placing tags on your items in a larger drawer together. Although this is also a way to organize code, it is very inefficient.
The namespace is coming to solve this problem. We can declare the same functions, classes, and constants in different namespaces without causing name conflicts. Essentially, namespace is nothing more than a way to mark PHP code by level.

Using namespace

One thing to note is that we are indirectly using namespaces. From PHP 5.3, all declarations (classes, functions, and constants) in non-user-defined namespaces belong to the global namespace by default.
The global namespace contains all PHP internal definitions, such as echo (), mysqli_connect (), and Exception classes. Because the global namespace does not have an independent identifier, it is often used as a global space ).

Define a namespace

The namespace must be the first statement in the PHP file. The only statement that can be used before the namespace is defined is the declare statement.
Defining a namespace is simple. you only need to use the keyword namespace. The namespace name must follow the naming rules for other identifiers in the PHP file.
The following is an example of defining a namespace:

The code is as follows:

namespace MyNamespace{ class Test{   }}

If you want to define a code block that belongs to a global space, the namespace keyword is also used, but the namespace name is not followed, as shown below:

The code is as follows:

namespace { class Test{   }}

We can even define multiple namespaces in a file, as shown below:

The code is as follows:

 

We can also divide a namespace into different files, and the processing programs included in the files will automatically merge them. Therefore, limiting a large number of namespaces to be defined in the same file is a good programming practice, just as we usually define a separate file for each class separately.

The code is as follows:

Note that {, which contains the namespace code block, is optional and optional. As a matter of fact, as long as we insist on defining only one namespace in a file, we can completely omit {, which can make our code look more concise.

Sub-namespace

A namespace can follow a specific level, just like a directory in our computer file system. Sub-namespaces are especially useful for structuring a project. For example, if your project needs to access the database, you may want to put all database-related code (such as database exception handling) in the same subdirectory.

To maintain flexibility, it is wise to put the sub-namespace in sub-directories. This will make your code structure clearer and make it easier to use autoloaders that follow PSR-0 standards.

PHP uses the backslash \ as the namespace separator. Interestingly, PHP has even considered using the smiley face :) as the namespace separator.

Sub-namespace definition example:

The code is as follows:

  

You can use as many sub-namespaces as possible:

The code is as follows:

   

Note that PHP does not support nested namespaces. the following code may cause a fatal error: Namespace declarations cannot be nested.

The code is as follows:

    

Call code from a namespace

If you want to instantiate a class, call a function, or use constants in different namespaces, you need to use the backslash \. They can be parsed from three perspectives:

1. Unlimited' name
2. limited name
3. fully qualified name

Unqualified Name)

This is the name, function, or constant of a class, but does not include any reference of the class name. If the namespace is still unfamiliar to you, this is your familiarity.

The code is as follows:

     

Qualified Name)

This is how we use sub-namespaces. Example:

The code is as follows:

      

Fully Qualified Name (Fully Qualified Name)

As mentioned above, the use of qualified names and unqualified names are all relative to the current namespace. The above two methods can only be used to access the current namespace and deeper sub-namespace.

If you want to access a higher level than the former namespace, you need to use a fully qualified name-an absolute path instead of a relative path. This can be attributed to adding a backslash \ at the beginning of the namespace \. Using a fully qualified name can let PHP know that this call starts from the global space, rather than the current namespace. Example:

The code is as follows:

       


For PHP internal functions, we do not need to use a fully qualified name. In the current namespace, PHP searches for the global space by calling a class or function with a non-existent unqualified name.
With this rule in mind, we can rewrite the internal functions of PHP as follows:

The code is as follows:

        ';}

Dynamic Call
PHP is a dynamic language. It can also be used to call namespaces. This is essentially the same as instantiating a variable class and containing a variable file. In a string, the namespace separator (\) used by PHP is also a metacharacter, so escape is required.

The code is as follows:

        

Namespace keyword
The keyword namespace can be used not only to define a namespace, but also to display the current namespace. at this time, it serves as the self keyword in the class.

The code is as follows:

         

_ NAMESPACE _ constant
Just as the self keyword cannot represent the name of the current class, the namespace keyword cannot be used to represent the name of the current namespace. The _ NAMESPACE _ keyword is used to solve this problem.

The code is as follows:

          


This keyword is useful for determining whether the current code starts from the namespace and can also be used to debug the code.

Import or alias
In PHP, namespaces can also be imported and imported as aliases. Only classes, interfaces, and namespaces can be imported (alias ). Import is a very useful and basic function in a namespace. It allows us to use external code packages without worrying about name conflicts. You can use the use keyword to import data. You can also use the as keyword to specify an alias during import.

The code is as follows:

use [name of class, interface or namespace] as [optional_custom_alias]

A fully qualified name can be replaced by an unqualified alias, so that we do not need to use a fully qualified name every time we use it to simplify the code. Import should be used at the highest level of the namespace or in the global space. Using the import function in the function scope is invalid syntax.

The code is as follows:

           

We can simplify the above code by using aliases:

The code is as follows:

            

Summary

Namespace is used to avoid definition conflicts and introduce more flexible and organized methods for code. One thing to note is that we are not obligated to use the namespace. it is a way of working combined with object-oriented. However, if a namespace is used, our code may reach a new level, and the code will look higher.

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.