The use of PHP namespaces (Namespace) is detailed

Source: Internet
Author: User
Tags define function
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:

Copy the code code as follows:


Example One
Write some logic code in front of the script

$path = "/";

Class Comment {}

namespace article;

?>

Example Two
Some characters are printed in front of the script


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

Copy the code code as follows:


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:

Copy the code code as follows:


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.

Copy the code code 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 {}

constants, functions, and classes that call the current space
Echo PATH; Message_board
Echo Getcommenttotal (); 300
$comment = new comment ();

constants, functions, and classes that call article space
Echo \article\path; Article
Echo \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:


I use this namespace to represent the article module under the blog
namespace Blog\article;

Class Comment {}


I use such a 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 ();

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:

Copy the code code as follows:


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:


namespace Blog\article;

Introducing script files
Include './common_inc.php ';

$filter _XSS = new FILTERXSS (); Fatal error: BLOG\ARTICLE\FILTERXSS class not found

$filter _XSS = new \FILTERXSS (); That's right

?>


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:


Create a Space blog
namespace Blog;

Class Comment {}

Unqualified name, which indicates 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 in front of class \

Fully qualified name, absolute in blog space
This call will be parsed into blog\comment ();
$article _comment = new \blog\comment (); The class is preceded by a backslash \

Fully qualified name, absolute in blog space
This call will be parsed into blog\article\comment ();
$article _comment = new \blog\article\comment (); The class is preceded by a backslash \


Create a blog's subspace article
namespace 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:


namespace Blog\article;

Class Comment {}


Create a BBS space (I have plans to open a forum)
namespace BBS;

Import a Namespace
Use blog\article;
You can invoke an element with a qualified name after importing the namespace
$article _comment = new Article\comment ();

Use aliases for namespaces
Use blog\article as Arte;
Use aliases instead of space names
$article _comment = new Arte\comment ();

Import a class
Use blog\article\comment;
You can invoke an element with an unqualified name after importing a class
$article _comment = new comment ();

Using Aliases for classes
Use 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:


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, the program generates fatal errors

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


namespace Blog\article;

Const PATH = '/blog/article ';

Class Comment {}


The namespace keyword represents 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 a string 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:


namespace 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

?>


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:


namespace Blog;

Import Common class
Use Blog\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 occurred: Common class does not exist

I want to call Blog\article\common with a 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 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.