How to use a PHP Namespace _ php instance

Source: Internet
Author: User
The most explicit purpose of a namespace is to solve the problem of duplicate names. In PHP, two functions or classes cannot have the same name. Otherwise, a fatal error occurs. In this case, the namespace can be solved by avoiding repeated names. The official documentation has already been very detailed [view]. I have made some practical and summary here.

The most explicit purpose of a namespace is to solve the problem of duplicate names. In PHP, two functions or classes cannot have the same name. Otherwise, a fatal error occurs. In this case, you only need to avoid repeated names. The most common practice is to define a prefix.

For example, there are two modules in the project: article and message board, each of which has a Comment class for processing user messages. Then I may want to add some information statistics functions for all users, such as the number of messages I want. At this time, it is good to call the methods provided by their Comment, but it is obviously not good to introduce their respective Comment classes at the same time. The Code will make an error, and rewriting any Comment in another place will also reduce the maintainability. At this time, only the class name can be reconstructed. I have agreed on a naming rule and added the module name before the class name, such as: Article_Comment, MessageBoard_Comment

As you can see, the name becomes very long, which means more code (at least more characters) will be written when Comment is used in the future ). In addition, if you want to add more integrated functions to each module or call each other in the future, you need to reconstruct the name in case of duplicate names. Of course, this problem was noticed at the beginning of the project and naming rules can be well avoided. Another solution is to use the namespace.


Note:

The constant mentioned in this article: The const keyword starting with PHP5.3 can be used outside the class. Both const and define are used to declare constants (their differences are not described in detail). However, in a namespace, define is used globally, while const acts on the current space. The constant I mentioned in this Article refers to the constant declared using const.


Basic
The namespace divides the code into different spaces (regions). The names of constants, functions, and classes of each space (which are called elements for laziness) do not affect each other, this is a bit similar to the 'package' concept we often mention.

To create a namespace, you must use the namespace keyword, as shown in the following code:

The Code is as follows:


// Create a namespace named 'Article'
Namespace Article;

?>


Note that no code exists before the first namespace of the current script file. The following statements are incorrect:

The Code is as follows:


// Example 1
// Write some logic code before the script

$ Path = "/";

Class Comment {}

Namespace Article;

?>

// Example 2
// Some characters are output before the script


Namespace Article;

?>


Why the first namespace? Because multiple namespaces can be created in the same script file.

Now I have created two namespaces. By the way, I have added a Comment class Element for each of these two namespaces:

The Code is as follows:


// Create a namespace named 'Article'
Namespace Article;

// This Comment is an element of the Article space.
Class Comment {}


// Create a namespace named 'messageboard'
Namespace MessageBoard;

// This Comment is an element of the MessageBoard space.
Class Comment {}
?>


You cannot directly call other elements between different spaces. You need to use the namespace Syntax:

The Code is as follows:


Namespace Article;

Class Comment {}


Namespace MessageBoard;

Class Comment {}

// Call the Comment class of the current space (MessageBoard)
$ Comment = new Comment ();

// Call the Comment class of the Article Space
$ Article_comment = new \ Article \ Comment ();

?>


We can see that when calling the Comment class in the article space in the MessageBoard space, a syntax like file path is used: \ space name \ element name

In addition to classes, functions and constants are used in the same way. Now I create new elements for the two spaces and output their values in the MessageBoard space.

The Code is as follows:


Namespace Article;

Const PATH = '/article ';

Function getCommentTotal (){
Return 100;
}

Class Comment {}


Namespace MessageBoard;

Const PATH = '/message_board ';

Function getCommentTotal (){
Return 300;
}

Class Comment {}

// Call constants, functions, and classes of the current space
Echo PATH; // message_board
Echo getCommentTotal (); // 300.
$ Comment = new Comment ();

// Call constants, functions, and classes in the Article Space
Echo \ Article \ PATH; // article
Echo \ Article \ getCommentTotal (); // 100
$ Article_comment = new \ Article \ Comment ();

?>


Then I did get the element data of the Article space.


Sub-Spaces
The Calling Syntax of a namespace makes sense like a file path. It allows us to customize the space to describe the relationship between each space.

Sorry, I forgot to mention that the article and message board modules are in the same blog project. If you use namespaces to express their relationships, the following is the case:

The Code is as follows:


// I use this namespace to indicate the article module in the blog.
Namespace Blog \ Article;

Class Comment {}


// I use this namespace to represent the message board module under the blog
Namespace Blog \ MessageBoard;

Class Comment {}

// Call the class of the current space
$ Comment = new Comment ();

// Call the class of the Blog/Article Space
$ Article_comment = new \ Blog \ Article \ Comment ();

?>


In addition, the sub-spaces can also define many layers, such as Blog \ Article \ Archives \ Date


Public Space
I have a common_inc.php script file, which contains some useful functions and classes:

The Code is as follows:


Function getIP (){}

Class FilterXSS {}

?>


Introduce this script into a namespace, and the elements in the script will not belong to this namespace. If no namespace is defined in this script, its elements are always in the public space:

The Code is as follows:


Namespace Blog \ Article;

// Introduce the script file
Include './common_inc.php ';

$ Filter_XSS = new FilterXSS (); // fatal error: the Blog \ Article \ FilterXSS class cannot be found

$ Filter_XSS = new \ FilterXSS (); // correct

?>


You can directly add \ before the element name to call the public space. Otherwise, the PHP parser considers that I want to call the elements in the current space. In addition to custom elements, PHP built-in elements are all public spaces.

I would like to mention that functions and constants in public spaces can be called normally without adding \ (I don't understand why PHP is doing this), but in order to correctly distinguish elements, we recommend that you add \ when calling a function \


Terms
Before talking about aliases and import, you need to know the terms about the three names of the space and how PHP parses them. The official documentation is very good, so I just used it.

1. A non-qualified name or a class name that does not contain a prefix, for example, $ comment = new Comment ();. If the namespace is Blog \ Article, Comment will be parsed as Blog \ Article \ Comment. If the code using Comment is not included in any namespace (in the global space), the Comment will be resolved to Comment.

2. A qualified name or a name containing a prefix, for example, $ comment = new Article \ Comment ();. If the current namespace is a Blog, the Comment will be parsed as Blog \ Article \ Comment. If the code using Comment is not included in any namespace (in the global space), the Comment will be resolved to Comment.

3. Fully qualified names or names that contain global prefix operators, such as $ comment = new \ Article \ Comment ();. In this case, the Comment is always parsed into the literal name (literal name) Article \ Comment in the code.

In fact, these three names can be analogous to file names (for example, comment. php), relative path name (such. /article/comment. php), absolute path name (for example,/blog/article/comment. php), which may be easier to understand.

I used several examples to represent them:

The Code is as follows:


// Create a space Blog
Namespace Blog;

Class Comment {}

// Undefined name, indicating the current Blog Space
// This call will be parsed into Blog \ Comment ();
$ Blog_comment = new Comment ();

// Specify the name, indicating the space relative to the Blog Space
// This call will be parsed into Blog \ Article \ Comment ();
$ Article_comment = new Article \ Comment (); // No backslice bar \

// Fully qualified name, indicating that it is definitely in the Blog Space
// This call will be parsed into Blog \ Comment ();
$ Article_comment = new \ Blog \ Comment (); // There is a reverse oblique rod in front of the class \

// Fully qualified name, indicating that it is definitely in the Blog Space
// This call will be parsed into Blog \ Article \ Comment ();
$ Article_comment = new \ Blog \ Article \ Comment (); // There is a reverse oblique rod in front of the class \


// Create a Blog sub-space Article
Namespace Blog \ Article;

Class Comment {}

?>


In fact, I have been using non-qualified names and fully qualified names. Now they can finally name them.


Alias and import
Alias and import can be seen as a shortcut for calling namespace elements. PHP does not support importing functions or constants.

They are implemented by using the use OPERATOR:

The Code is as follows:


Namespace Blog \ Article;

Class Comment {}


// Create a BBS space (I plan to open a Forum)
Namespace BBS;

// Import a namespace
Use Blog \ Article;
// After the namespace is imported, you can use a limited name to call the element.
$ Article_comment = new Article \ Comment ();

// Alias used for the namespace
Use Blog \ Article as Arte;
// Replace the space name with an alias
$ Article_comment = new Arte \ Comment ();

// Import a class
Use Blog \ Article \ Comment;
// You can use a non-qualified name to call an element after the class is imported.
$ Article_comment = new Comment ();

// Use aliases for Classes
Use Blog \ Article \ Comment as Comt;
// Replace the space name with an alias
$ Article_comment = new Comt ();

?>


I noticed that what if the current space has the same name element when importing elements? Obviously, a fatal error occurs in the result.

Example:

The Code is as follows:


Namespace Blog \ Article;

Class Comment {}


Namespace BBS;

Class Comment {}

Class Comt {}


// Import a class
Use Blog \ Article \ Comment;
$ Article_comment = new Comment (); // conflicts with the Comment of the current space, causing a fatal error in the program

// Use aliases for Classes
Use Blog \ Article \ Comment as Comt;
$ Article_comment = new Comt (); // conflicts with the Comt of the current space, causing a fatal error in the program

?>


Dynamic call
PHP provides the namespace keyword and the _ NAMESPACE _ magic constant dynamic access element, __namespace _ can be dynamically accessed by combining strings:

The Code is as follows:


Namespace Blog \ Article;

Const PATH = '/Blog/article ';

Class Comment {}


// The namespace keyword indicates the current space.
Echo namespace \ PATH; // Blog/article
$ Comment = new namespace \ Comment ();

// The value of the magic constant _ NAMESPACE _ is the name of the current space.
Echo _ NAMESPACE __; // Blog \ Article
// Can be combined into strings and called
$ Comment_class_name = _ NAMESPACE _. '\ Comment ';
$ Comment = new $ comment_class_name ();

?>


String format call problems

In the above dynamic call example, we see the string-form dynamic call method. If you want to use this method, pay attention to two issues.

1. special characters may be escaped when double quotation marks are used

The Code is as follows:


Namespace Blog \ Article;

Class name {}

// I want to call Blog \ Article \ name
$ Class_name = _ NAMESPACE _. "\ name"; // However, \ n will be escaped as a line break

$ Name = new $ class_name (); // a fatal error occurs.

?>


2. It is not considered as a qualified name

When compiling the script, PHP determines the space where the element is located and the import status. When parsing scripts, strings can only be considered as non-qualified names and fully qualified names, but never as qualified names.

The Code is as follows:


Namespace Blog;

// Import the Common class
Use Blog \ Article \ Common;
// I want to call Blog \ Article \ Common with an undefined name
$ Common_class_name = 'common ';
// It is actually treated as a non-qualified name, which indicates the Common class of the current space. However, I have not created a Common class for the current class.
$ Common = new $ common_class_name (); // fatal error: the Common class does not exist

// I want to use a limited name to call Blog \ Article \ Common
$ Common_class_name = 'Article \ common ';
// Actually, it is treated as a fully qualified name, which indicates the Common class in the Article space. However, I only define the Blog \ Article space instead of the Article space.
$ Common = new $ common_class_name (); // a fatal error occurs: The Article \ Common class does not exist.


Namespace Blog \ Article;

Class Common {}

?>


Summary
I have just been in touch with the PHP namespace and cannot give some practical suggestions. I personally think that namespaces have powerful functions and functions. If you want to write plug-ins or generic Libraries, you no longer have to worry about duplicate names. However, if the project is implemented to a certain extent and you need to add a namespace to solve the duplicate name problem, I don't think the workload will be less than rebuilding the name. I have to admit that its syntax will increase the complexity of the project. Therefore, we should plan the project well from the very beginning and develop a naming convention.

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.