Usage of PHP Namespace _ PHP Tutorial

Source: Internet
Author: User
PHP Namespace usage details. For the namespace, 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 name duplication. if the namespace is not allowed in PHP, the official document has already been described in detail [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.

Bytes. The most explicit purpose of the namespace is to solve the problem of duplicate names, which is not allowed in PHP...

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.