Namespace in PHP

Source: Internet
Author: User

Namespace in PHP

After exploring the closure, [view] And then explore the namespace.

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.Duplicate namesPHP does not allow two functions or classes to 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, the project has two modules:ArticleAndMessage board, Each of which has a class for processing user messagesComment. Then I may want to add some information statistics functions for all users, such as the number of messages I want. Call them at this timeCommentThe provided methods are good practices, but they also introduce their respectiveCommentClass obviously does not work, the code will go wrong, rewrite any one in another placeCommentIt also reduces 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, as shown in the following figure:Article_Comment,MessageBoard_Comment

As you can see, the name becomes very long, which means to be used later.CommentWrite more code (at least more characters ). 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: PHP5.3ConstKeywords can be used outside the class.ConstAndDefineThey are all used to declare constants (their differences are not detailed), but in the namespace,DefineIs global, whileConstIt is applied to the current space. The constant I mentioned in this Article refers to the useConstDeclared constant.

 

 

Basic

The namespace divides the code into different spaces (regions). constants, functions, and classes of each space (which are called below for laziness)Element.

To create a namespace, you must useNamespaceKeyword:

<? Php // create a namespace Article named 'Article';?>

 

Note that no code exists before the first namespace of the current script file.ErrorOf:

// Example 1 // some logic code is written before the script <? Php $ path = "/"; class Comment {} namespace Article;?>
// Example 2 // some characters are output before the script

 

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 one for each of them.CommentClass element:

<? Php // create a namespace Article named 'Article; // This Comment belongs to the Article space element class Comment {} // create a namespace MessageBoard named 'messageboard; // This Comment belongs to the MessageBoard space element class Comment {}?>

 

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

<? Phpnamespace 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 ();?>

 

As you can seeMessageBoardSpace CallArticleSpaceCommentClass, a syntax like file path is used:\ Space name \ element name

In addition to classes, the usage of functions and constants is the same. Next I create new elements for the two spaces andMessageBoardSpace outputs their values.

<? Phpnamespace Article; const PATH = '/article'; function getCommentTotal () {return 100;} class Comment {} namespace MessageBoard; const PATH ='/message_board '; function getCommentTotal () {return 300;} class Comment {} // call the current space's constants, functions, and echo PATH; // message_boardecho getCommentTotal (); // 300 $ comment = new Comment (); // call constants, functions, and classes of the Article Space echo \ Article \ PATH; // articleecho \ Article \ getCommentTotal (); // 100 $ Article_comment = new \ Article \ Comment ();?>

 

Then I did getArticleSpace element data.

 

 

Sub-Spaces

The Calling Syntax of a namespace makes sense like a file path. It allows usCustomSubspacesDescriptionThe relationship between spaces.

Sorry, I forgot to say,ArticleAndMessage boardBoth modules are in the sameBlogWithin the project. If you use namespaces to express their relationships, the following is the case:

<? Php // I use this namespace to indicate the namespace blog \ article module in the Blog; class Comment {} // I use this namespace to indicate the message board module namespace blog \ MessageBoard under the Blog; class Comment {} // class that calls 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 define many layers, suchBlog \ Article \ Archives \ Date

 

 

Public Space

I haveCommon_inc.phpThe script file contains some useful functions and classes:

<?phpfunction 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 remainPublic SpaceMedium:

<? Phpnamespace Blog \ Article; // introduce the script file include '. /common_inc.php '; $ filter_XSS = new FilterXSS (); // fatal error: unable to find Blog \ Article \ FilterXSS class $ filter_XSS = new \ FilterXSS (); // correct?>

 

You can call a public space directly by adding\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.

 

These three names can be analogous to file names (for exampleComment. php), Relative path name (for example./Article/comment. php), Absolute path name (such/Blog/article/comment. php), Which may be easier to understand.

I used several examples to represent them:

<? Php // create a space Blognamespace Blog; class Comment {} // unlimitedly name, indicating that the current Blog space // this call will be parsed into Blog \ Comment (); $ blog_comment = new Comment (); // a qualified name, indicating that the call will be parsed into Blog \ Article \ Comment () relative to the Blog space (); $ article_comment = new Article \ Comment (); // There is no reverse oblique rod before the class \ // fully qualified name, it indicates that the call will be parsed into Blog \ Comment (); $ article_comment = new \ Blog \ Comment (); // The class is preceded by a reverse slash \ // fully qualified name, indicating that the call is definitely in the Blog space // It will be parsed into Blog \ Article \ Comment (); $ article_comment = new \ Blog \ Article \ Comment (); // There Is A backslice bar in front of the class \ // The sub-space for creating a Blog Articlenamespace 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 all useUseOPERATOR:

<? Phpnamespace 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 (); // use the alias use Blog \ Article as Arte for the namespace; // use an alias to replace the space name $ article_comment = new Arte \ Comment (); // import a class use Blog \ Article \ Comment; // after the class is imported, you can call the element $ article_comment = new Comment () using a non-qualified name; // use the alias use Blog \ Article \ Comment as Comt for the class; // use an alias to replace the space name $ article_commen T = 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:

<? Phpnamespace Blog \ Article; class Comment {} namespace BBS; class Comment {} Class Comt {} // import a class use Blog \ Article \ Comment; $ article_comment = new Comment (); // conflict with the Comment of the current space, causing a fatal error in the program // use the alias use Blog \ Article \ Comment as Comt for the class; $ article_comment = new Comt (); // conflicts with the Comt of the current space, causing a fatal error in the program?>

 

 

Dynamic call

PHP providesNamespaceKeyword and_ NAMESPACE __Dynamic access elements of magic constants,_ NAMESPACE __You can use a combination of strings for dynamic access:

<? 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 name of the current space echo _ NAMESPACE __; // Blog \ Article // can be combined into a string and call $ 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

<? Phpnamespace Blog \ Article; class name {} // I want to call Blog \ Article \ name $ class_name = _ NAMESPACE __. "\ name"; // But \ n will be escaped as a linefeed $ name = new $ class_name (); // is a fatal error?>

 

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.

<? Phpnamespace Blog; // import the Common class use Blog \ Article \ Common; // I want to call Blog \ Article \ Common $ common_class_name = 'common' using a non-qualified name '; // It is actually treated as a non-qualified name, which indicates the Common class of the current space, but my current class does not create the Common class $ common = new $ common_class_name (); // fatal error: the Common class does not exist // I want to use a qualified name to call Blog \ Article \ Common $ common_class_name = 'Article \ common '; // It is actually 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. Error: The namespace Blog \ Article; class Common {}?> does not exist in the Article \ Common class.

 

 

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.