PHP namespace details

Source: Internet
Author: User
This article mainly introduces the namespace in PHP and explains the namespace) 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 it.


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:


<? Php
Namespace MyNamespace {
}

Namespace MySecondNamespace {
}

Namespace {
}

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 a backslash as the namespace separator. Interestingly, PHP has even considered using a smiley face :) as the namespace separator.

Sub-namespace definition example:

The code is as follows:


<? Php
Namespace MyProject \ Database

Class Connection {
}


You can use as many sub-namespaces as possible:

The code is as follows:


<? Php
Namespace MyProject \ Blog \ Auth \ Handler \ Social;

Class Twitter {
}

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:


<? Php
Namespace MyProject {
Namespace Database {
Class Connection {}
}
}

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:


<? Php
Namespace MyProject;

Class MyClass {
Static function static_method ()
{
Echo 'Hello, world! ';
}
}

// Unqualified name, resolves to the namespace you are currently in (MyProject \ MyClass)
MyClass: static_method ();

Qualified Name)

This is how we use sub-namespaces. Example:

The code is as follows:


<? Php
Namespace MyProject;

Require 'myproject/database/connection. php ';

// Qualified name, instantiating a class from a sub-namespace of MyProject
$ Connection = new Database \ Connection ();

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:


<? Php
Namespace MyProject \ Database;

Require 'myproject/fileaccess/input. php ';

// Trying to access the MyProject \ FileAccess \ Input class
// This time it will work because we use the fully qualified name, note the leading backslash
$ Input = new \ MyProject \ FileAccess \ Input ();


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:

<? Php
Namespace MyProject;

Var_dump ($ query); // Overloaded
\ Var_dump ($ query); // Internal

// We want to access the global Exception class
// The following will not work because there's no class called Exception in the MyProject \ Database namespace and unqualified class names do not have a fallback to global space
// Throw new Exception ('query failed! ');

// Instead, we use a single backslash to indicate we want to resolve from global space
Throw new \ Exception ('ailed! ');

Function var_dump (){
Echo 'overloaded global var_dump ()!
';
}

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:


<? Php
Namespace OtherProject;

$ Project_name = 'myproject ';
$ Package_name = 'database ';
$ Class_name = 'connection ';

// Include a variable file
Require strtolower ($ project_name. '/'. $ package_name. '/'. $ class_name). '. php ';

// Name of a variable class in a variable namespace. Note how the backslash is escaped to use it properly
$ Fully_qualified_name = $ project_name. '\'. $ package_name. '\'. $ class_name;

$ Connection = new $ fully_qualified_name ();

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:


<? Php
Namespace MyProject;

Function run ()
{
Echo 'running from a namespace! ';
}

// Resolves to MyProject \ run
Run ();
// Explicitly resolves to MyProject \ run
Namespace \ run ();

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


<? Php
Namespace MyProject \ Database;

// 'Myproject \ database'
Echo _ NAMESPACE __;


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:


<? Php
Namespace OtherProject;

// This holds the MyProject \ Database namespace with a Connection class in it
Require 'myproject/database/connection. php ';

// If we want to access the database connection of MyProject, we need to use its fully qualified name as we're in a different name space
$ Connection = new \ MyProject \ Database \ Connection ();

// Import the Connection class (it works exactly the same with interfaces)
Use MyProject \ Database \ Connection;

// Now this works too! Before the Connection class was aliased PHP wocould not have found an OtherProject \ Connection class
$ Connection = new Connection ();

// Import the MyProject \ Database namespace
Use MyProject \ Database;

$ Connection = new Database \ Connection ()


We can simplify the above code by using aliases:

The code is as follows:


<? Php
Namespace OtherProject;

Require 'myproject/database/connection. php ';

Use MyProject \ Database \ Connection as MyConnection;

$ Connection = new MyConnection ();

Use MyProject \ Database as MyDatabase;

$ Connection = new MyDatabase \ Connection ();

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.

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.