PHP Namespaces and mutable functions

Source: Internet
Author: User
Tags define function naming convention create blog

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 you can resolve the namespace, the official documentation has been described in detail [view], I've done a little 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 can see, the name becomes very long, That means more code (at least a lot of 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. Note: The constants mentioned in this article: PHP5.3 Start 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. The underlying namespace divides code into different spaces (regions), and each space's constants, functions, and classes (for the sake of laziness, the names of which I call elements below) do not affect each other, which is somewhat similar to what we often refer to as ' encapsulation‘the concept. Creating a namespace requires the use of the namespace keyword, so: Copy the code as follows: <?php//create a name of' Article 'the namespace 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 wrong: Copy the Code as follows://Example one//write some logic code in front of the script <?php$path = "/"; class Comment {} namespace article;? >//Example II//output some characters in front of the script  named' Article 'the namespace namespace article;//this Comment belongs to the element of article space class Comment {}//creates a named' Messageboard 'the namespace namespace messageboard;//this Comment element that belongs to the Messageboard space class Comment {}?> can not invoke other elements directly between different spaces, Syntax to use namespaces: Copy code code as follows: <?phpnamespace article;class Comment {}namespace messageboard;class Comment {}// Call the current space (messageboard) of the comment class $comment = new Comment ();//Call article space Comment class $article_comment = new \article\comment ( );? > can see that when calling the comment class in the article space in the messageboard space, a file-path-like syntax is used: \ space name \ element name In addition to the class, the use of functions and constants is the same, below I created a new element for two spaces, and output their values in the 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. The call syntax for the subspace 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 relationship, it is: Copy the code as follows: <?php//I use this namespace to represent the article module under 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 ();// The class calling 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 code code as follows: &LT;? Phpfunction GetIP () {}class FILTERXSS {}?> introduces this script in a namespace, and the elements in the script do not belong to this namespace.  If no other namespace is defined in this script, its elements are always in public space: the copy Code code is 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 (); The correct way to call public space is to add \?> directly to the element name, 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 proposed call to the function when the name term in the alias and before the import, you need to know about the space three names of terms, And how PHP interprets 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 code code as follows: <?php//Create space blognamespace blog;class Comment {}//unqualified name, indicates 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 absolute 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 in front of it, 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 backslash//create Blog subspace Articlenamespace blog\article;class Comment {}?> I've been using unqualified names and fully qualified names before, and now they can finally name them. Aliases and import aliases and imports can be seen 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: the copy code code is as follows: <?phpnamespace blog\article;class Comment {}//Create a BBS space (I intend to open a forum) namespace bbs;// Import a namespace use blog\article;//to call an element with a qualified name after importing a namespace $article_comment = new Article\comment ();//alias for namespace using Blog\article as arte;//use aliases instead of space names $article_comment = new Arte\comment ();//Import a class use blog\article\comment;//importing a class can invoke an element with an unqualified name $article_ Comment = new Comment ()//Use Alias for class using blog\article\comment as comt;//use alias instead of space name $article_comment = new COMT ();? > I notice 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. Example: Copy code code as follows: &LT;?Phpnamespace blog\article;class Comment {}namespace bbs;class Comment {}class Comt {}//Import a class use blog\article\comment; $a Rticle_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 (); Conflict with the COMT of the current space, the program generates a fatal error?> dynamic invocation of PHP provides NAMESPACE keyword and __namespace__ magic constant dynamic access elements, __namespace__  can be dynamically accessed by combining strings: The copy Code code is as follows: <?phpnamespace blog\article;const PATH ='/blog/article 'The 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 ();? > In the case of a dynamic call above the string call problem, we see a dynamic invocation in the form of a string, and there are two issues to note if you want to use this approach. 1. When using double quotation marks, special characters may be escaped copy code code is as follows: <?phpnamespace blog\article;class name {}//I want 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. It is not considered a qualified name. PHP determines the space in which the element resides and the import situation when compiling the script. 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 with unqualified names _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$common_class_name with a qualified name =' Article\common ', //is actually treated as a fully qualified name and represents the common class under the article space, but I have defined blog\article space instead of article space $common = new $common _class_name (); /Fatal error: Article\common class does not exist namespace Blog\article;class Common {}?> Summary I have just contacted Php's namespace, and I can't give some advice without 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. 



<?PHPInterfaceiuser{functionget (); functionset (); }    classUserImplementsiuser{ Public functionget () {Echo"Use"; }         Public functionset () {Echo"Me"; }    }    $user=NewUser (); $user->get ().$user->set ();


PHP Namespaces and mutable functions

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.