How to use PHP namespaces in detail

Source: Internet
Author: User
Namespace one of the most explicit purposes is to solve the problem of duplicate names, PHP does not allow two functions or classes to appear the same name, otherwise it will produce a fatal error. In this case, as long as you avoid naming duplicates can be resolved, the most common practice is to contract a prefix.

Example: There are two modules in the project: article and Message board, each of which has a class comment that handles user messages. Then I might want to add some stats to all of my users ' messages, such as the number of messages I want to get. It is good practice to call them comment the methods provided, but it is obviously not possible to introduce the respective comment classes, and the code will go wrong, and rewriting any of the comment in another place will also reduce maintainability. That's when the class name can only be refactored, and I've contracted a naming convention to precede the class name with the module name, like this: Article_comment, messageboard_comment

As you can see, the name becomes very long, which means that more code (at least more characters) will be written later when using comment. Furthermore, if you want to add more integration functions to each module, or call each other, the name will need to be reconstructed when the duplicate names occur. Of course, when the project began to notice the problem, and the naming rules can be very good to avoid the problem. Another workaround is to consider using namespaces.

Indicate:

Constants mentioned in this article: PHP5.3 the start of the Const keyword can be used outside of the class. Both const and define are used to declare constants (their differences are not detailed), but in namespaces the Define function is global and the const acts on the current space. The constants I mentioned in this article refer to constants declared with Const.

Basis
Namespaces divide code into different spaces (regions), constants, functions, and classes (for laziness, which I call elements below) do not affect each other, which is somewhat similar to the concept of ' encapsulation ' that we often refer to.

Creating a namespace requires the use of the namespace keyword, so that:
Copy the code code as follows:

<?php//create a namespace named ' article ' namespace article; >

Note that there cannot be any code in front of the first namespace of the current script file, and the following syntax is incorrect:
Copy the code code as follows:

Example One
Write some logic code in front of the script

<?php$path = "/"; class Comment {}namespace article;? >

Example Two
Some characters are printed in front of the script


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

Below I created two namespaces, and by the way I added a comment class element to each of the two spaces:
Copy the code code as follows:

<?php//create a namespace named ' article ' namespace article;//this Comment the element belonging to the article space class Comment {}//Create a name of ' messageboard ' The namespace of the namespace messageboard;//this Comment element that belongs to the Messageboard space class Comment {}?>

You cannot call other elements directly between different spaces, and you need to use the syntax of the namespace:
Copy the code code as follows:

<?phpnamespace article;class Comment {}namespace messageboard;class Comment {}//calls the current space (messageboard) Comment class $ Comment = new comment ();//Call article space Comment class $article_comment = new \article\comment ();? >

As you can see, when you call 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, the use of functions and constants is the same, I create new elements for two spaces, and output their values in messageboard space.
Copy the code code as follows:

<?phpnamespace article;const PATH = '/article '; function Getcommenttotal () {    return 100;} Class Comment {}namespace messageboard;const PATH = '/message_board '; function Getcommenttotal () {    return 300;} Class Comment {}//calls the constant, function, and class echo PATH of the current space; Message_boardecho getcommenttotal (); 300$comment = new Comment ();//The constants, functions, and classes that call article space echo \article\path; Articleecho \article\getcommenttotal (); 100$article_comment = new \article\comment ();? >

Then I did get the element data for the article space.

Sub-space
The invocation syntax of the namespace is justified as a file path, allowing us to customize the subspace to describe the relationships between the spaces.

Sorry I forgot to say, article and message board these two modules are actually in the same blog project. If you use namespaces to express their relationships, this is the case:
Copy the code code as follows:

<?php//I use such a namespace to represent the article module under the blog namespace Blog\article;class Comment {}//I use such a namespace to represent the message under the blog Board Module namespace Blog\messageboard;class Comment {}//Call the current space class $comment = new Comment ();//Call Blog\article Space class $article_ Comment = new \blog\article\comment ();? >

Also, subspace can define many levels, such as Blog\article\archives\date

Public space
I have a common_inc.php script file with some useful functions and classes:
Copy the code code as follows:

<?phpfunction GetIP () {}class FILTERXSS {}?>

This script is introduced into a namespace, and the elements in the script do not belong to the namespace. If no other namespace is defined in this script, its elements are always in public space:
Copy the code code as follows:

<?phpnamespace blog\article;//Introduction script file include './common_inc.php '; $filter _xss = new FILTERXSS (); Fatal error: Unable to find BLOG\ARTICLE\FILTERXSS class $FILTER_XSS = new \filterxss (); Correct?>

The way to call public space is directly before the element name plus \ on it, otherwise the PHP parser will think I want to invoke the element under the current space. In addition to the custom elements, including PHP's own elements, all belong to the public space.

To mention, in fact, the functions and constants of the public space do not have to add \ can also be normal call (do not understand why PHP to do so), but in order to correctly distinguish between the elements, or the recommendation to call the function when adding \

Name term
Before you say aliases and imports, you need to know the terminology about the space three names and how PHP parses them. The official documentation was very good, and I took it directly.

1. Unqualified name, or class name that does not contain a prefix, for example $comment = new comment ();. If the current namespace is blog\article,comment, it will be resolved to blog\article\comment. If the code that uses comment is not included in the code in any namespace (in global space), then comment is resolved to comment.

2. Qualify the name, or include the name of the prefix, for example $comment = new Article\comment ();. If the current namespace is a blog, Comment will be parsed as blog\article\comment. If the code that uses comment is not included in the code in any namespace (in global space), then comment is resolved to comment.

3. Fully qualified name, or contains the name of the global prefix operator, for example $comment = new \article\comment ();. In this case, Comment is always parsed into the literal name in the code (literal name) article\comment.

You can actually compare these three names to filenames (such as comment.php), relative pathname (for example,./article/comment.php), Absolute pathname (for example,/blog/article/comment.php), which may be easier to understand.

I used a few examples to represent them:
Copy the code code as follows:

<?php//creates a space blognamespace Blog;class Comment {}//Unqualified name that represents the current Blog space//This call will be parsed into blog\comment (); $blog _comment = new Comment ();//qualified name, indicating relative to the Blog space//This call will be parsed into blog\article\comment (); $article _comment = new Article\comment (); There is no backslash \//fully qualified name in front of the class, which means it is absolutely in the Blog space//This call will be parsed into blog\comment (); $article _comment = new \blog\comment (); The class has a backslash \//fully qualified name, which means it is absolutely in the Blog space//This call will be parsed into blog\article\comment (); $article _comment = new \blog\article\comment (); class preceded by a backslash \//create a Blog subspace Articlenamespace blog\article;class Comment {}?>

In fact, I've been using unqualified names and fully qualified names before, and now they can finally call out their names.

Aliases and imports
Aliases and imports can be thought of as a quick way to invoke namespace elements. PHP does not support importing functions or constants.

They are all implemented by using the use operator:
Copy the code code as follows:

<?phpnamespace blog\article;class Comment {}//Create a BBS space (I'm going to open a forum) namespace bbs;//Import a namespace use blog\article;// The namespace can be invoked with qualified names after importing the namespaces $article_comment = new Article\comment ();//use aliases for namespaces using Blog\article as arte;//use aliases instead of space names $article_ Comment = new arte\comment ();//Import a class use blog\article\comment;//import a class to invoke an element with an unqualified name $article_comment = new comment ();// Use aliases for classes using Blog\article\comment as comt;//use aliases instead of space names $article_comment = new COMT (); >

I've noticed what happens if the element is imported with the same name element in the current space? It is obvious that a fatal error will occur.

Cases:
Copy the code code as follows:

<?phpnamespace blog\article;class Comment {}namespace bbs;class Comment {}class Comt {}//Import a class use Blog\article\comme NT; $article _comment = new comment (); Conflicts with the Comment of the current space, the program produces fatal errors//uses aliases for classes use blog\article\comment as COMT; $article _comment = new COMT (); Conflicts with the COMT of the current space, the program generates fatal errors?>

Dynamic invocation
PHP provides dynamic access elements for the namespace keyword and namespace Magic constants, namespace can be dynamically accessed by combining strings:
Copy the code code as follows:

<?phpnamespace blog\article;const PATH = '/blog/article '; class Comment {}//namespace keyword indicates the current space echo Namespace\path; Blog/article$comment = new Namespace\comment ();//The value of the magic constant __namespace__ is the current space name Echo __namespace__; blog\article//can be combined into strings and called $comment_class_name = __namespace__. ' \comment '; $comment = new $comment _class_name ();? >

Question of string form call

In the above example of dynamic invocation, we see a dynamic invocation in the form of a string, and there are two issues to note if you want to use this method.

    1. Special characters may be escaped when using double quotes
      Copy the code code as follows:

<?phpnamespace blog\article;class Name {}//I was trying to call Blog\article\name$class_name = __namespace__. "\name"; But \ nthe will be escaped as a newline character $name = new $class _name (); Fatal error occurred?>
    1. Not considered a qualified name

PHP compiles the script to determine the space in which the element resides, as well as the import situation. When parsing a script, a string invocation can only be considered a unqualified name and a fully qualified name, and it never could be a qualified name.
Copy the code code as follows:

<?phpnamespace blog;//import Common class use blog\article\common;//I want to call Blog\article\common$common_class_name = ' with unqualified name Common ';//is actually treated as an unqualified name and represents the Common class of the current space, but my current class does not create Common class $common = new $common _class_name (); Fatal error: Common class does not exist//I want to call blog\article\common$common_class_name = ' Article\common ' with qualified name;//actually be treated as fully qualified name, It also represents the common class under article space, but I have defined only blog\article space below article space $common = new $common _class_name (); Fatal error occurred: Article\common class does not exist namespace Blog\article;class Common {}?>

Summarize
I'm just in touch with PHP's namespace, and I can't give you some advice that doesn't make any practice. I personally think that the role and function of the namespace is very powerful, if you want to write plug-ins or general-purpose library can no longer worry about the name problem. However, if the project to a certain extent, through the addition of namespaces to solve the problem of duplicate names, I think the workload will not be less specific. Also have to admit that its syntax adds a certain degree of complexity to the project, so it should be well planned from the start of the project, and a naming convention should be developed.

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.