The use of PHP namespaces (Namespace) is detailed

Source: Internet
Author: User
Tags aliases define function naming convention php script

For namespaces, the official documentation has been described in detail [view], and I've done a bit of practice and summary here.

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:
<?  // 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 :

<? PHP // example I//write some logic code in front of the script $path = "/"; class Comment {}namespace article; // example two//in front of the script output some characters phpnamespace article;? >

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:


<?  // Create a namespace named ' article ' namespace article; // this comment element that belongs to the article space class Comment {} // create a namespace named ' Messageboard ' 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:


<? php namespace article; class Comment {}namespace messageboard; class Comment {} // Call the comment class for the current space (messageboard) $comment New Comment (); // Call the comment class for article space $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.


<?php namespace article;ConstPATH = '/article ';functiongetcommenttotal () {return100;}classComment {}namespace messageboard;ConstPATH = '/message_board ';functiongetcommenttotal () {return300;}classComment {}//constants, functions, and classes that call the current spaceEchoPATH;///message_boardEchoGetcommenttotal ();// -$comment=NewComment ();//constants, functions, and classes that call article spaceEcho\article\path;///articleEcho\article\getcommenttotal ();// -$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:

<?PHP//I use this namespace to represent the article module under the blognamespace Blog\article;classComment {}//I use such a namespace to represent the message board module under the blognamespace Blog\messageboard;classComment {}//call the class of the current space$comment=NewComment ();//class that calls Blog\article space$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:


<?  function  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:
<? php namespace blog\article; // Introducing script Files include './common_inc.php '; $filter _XSS New // Fatal error: BLOG\ARTICLE\FILTERXSS class not found $filter _XSS New // 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:

<?PHP//Create a space blognamespace Blog;classComment {}//Unqualified name, indicates the current Blog space//This call will be parsed into blog\comment ();$blog _comment=NewComment ();//The qualified name, relative to the Blog space//This call will be parsed into blog\article\comment ();$article _comment=NewArticle\comment ();//there is no backslash//fully qualified name in front of the class, which means that the call will be parsed into blog\comment (), which is absolutely in the Blog space.$article _comment=New\blog\comment ();//The class is preceded by a backslash//fully qualified name, which means that 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;classComment {}?>

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:
<?php namespace blog\article;classComment {}//Create a BBS space (I have plans to open a forum)namespace BBS;//Import a namespace Useblog\article;//you can invoke an element with a qualified name after importing the namespace$article _comment=Newarticle\comment ();//use aliases for namespaces UseBlog\article asArte;//use aliases instead of space names$article _comment=Newarte\comment ();//Import a class Useblog\article\comment;//you can invoke an element with an unqualified name after importing a class$article _comment=NewComment ();//using aliases for classes UseBlog\article\comment asCOMT;//use aliases instead of space names$article _comment=NewComt ();?>


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:
<?php namespace blog\article;classComment {}namespace BBS;classComment {}ClassCOMT {}//Import a class Useblog\article\comment;$article _comment=NewComment ();//conflicts with the comment of the current space, the program generates fatal errors//uses aliases for classes UseBlog\article\comment asCOMT;$article _comment=NewCOMT ();//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:
<?php namespace blog\article;ConstPATH = '/blog/article ';classComment {}//The namespace keyword represents the current spaceEchoNamespace\path;///blog/article$comment=Newnamespace\comment ();//the value of the magic constant __namespace__ is the current space nameEcho__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 quotation marks

Copy the code code as follows:
<? php namespace blog\article; class name {} // I was trying to call Blog\article\name . $class _name // but \ nthe will be escaped as a newline character. $name New $class _name // fatal error occurred ?>


2. Does not consider 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:
<?php namespace Blog;//Import Common class UseBlog\article\common;//I want to call Blog\article\common with an unqualified name$common _class_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 a common class$common=New $common _class_name();//Fatal error: Common class does not exist//I want to call Blog\article\common with qualified name$common _class_name= ' Article\common ';//It will actually be treated as a fully qualified name, and it will represent the common class under the article space, but I have defined only blog\article space, not article space .$common=New $common _class_name();//fatal error occurred: Article\common class does not existnamespace Blog\article;classCommon {}?>


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.

The use of PHP namespaces (Namespace) is detailed

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.