Home  >  Article  >  Backend Development  >  Detailed usage of PHP namespace

Detailed usage of PHP namespace

小云云
小云云Original
2018-03-01 10:35:292320browse

One of the clearest purposes of namespaces is to solve the problem of duplicate names. PHP does not allow two functions or classes to have the same name, otherwise a fatal error will occur. In this case, it can be solved as long as you avoid naming duplication. The most common way is to agree on a prefix.

Example: There are two modules in the project: article and message board, each of which has a class Comment for processing user messages. Later, I may want to add some information statistics functions for all user messages. For example, I want to get the number of all messages. At this time, it is a good idea to call the methods provided by their Comments, but it is obviously not possible to introduce their respective Comment classes at the same time. The code will make errors, and rewriting any Comment in another place will also reduce maintainability. At this time, I can only reconstruct the class name. I agreed on a naming rule and added the module name in front of the class name, like this: Article_Comment, MessageBoard_Comment

As you can see, the name becomes very long, which means When I use Comment in the future, I will write more code (at least more characters). Moreover, if you want to add more integration functions to each module in the future, or call each other, you will need to reconstruct the names when duplicate names occur. Of course, this problem can be avoided by noticing this problem at the beginning of the project and specifying naming rules. Another solution could be to use namespaces.

Note:

Constants mentioned in this article: starting from PHP5.3, the const keyword can be used outside the class. Both const and define are used to declare constants (their differences are not detailed), but in a namespace, define acts globally, while const acts on the current space. The constants I mentioned in the article refer to constants declared using const.

Basics
Namespace divides the code into different spaces (areas), and the names of constants, functions, and classes in each space (to be lazy, I will call them elements below) do not affect each other. , This is somewhat similar to the concept of 'encapsulation' that we often mention.

To create a namespace, you need to use the namespace keyword, like this:
Copy the code as follows:

<?php//创建一个名为&#39;Article&#39;的命名空间namespace Article;?>

It should be noted that the first namespace of the current script file cannot be preceded by Any code, the following writing is wrong:
Copy the code as follows:

//Example 1
//Write some logic code in front of the script

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

/ /Example 2
//Some characters are output in front of the script

<html></html><?php
    namespace Article;?>

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

Below I created two namespaces, and added a Comment class element to each of these two spaces:
Copy the code The code is as follows:

<?php//创建一个名为&#39;Article&#39;的命名空间namespace Article;//此Comment属于Article空间的元素class Comment { }//创建一个名为&#39;MessageBoard&#39;的命名空间namespace MessageBoard;//此Comment属于MessageBoard空间的元素class Comment { }?>

There is no difference between different spaces You can directly call other elements by using the namespace syntax:
Copy the code as follows:

<?phpnamespace Article;class Comment { }namespace MessageBoard;class Comment { }//调用当前空间(MessageBoard)的Comment类$comment = new Comment();//调用Article空间的Comment类$article_comment = new \Article\Comment();?>

As you can see, when calling the Comment class in the article space in the MessageBoard space, a method like The syntax of the file path: \space name\element name

Except for classes, the usage of functions and constants is the same. Below I create new elements for the two spaces and output them in the MessageBoard space. their values.
Copy the code as follows:

<?phpnamespace Article;const PATH = &#39;/article&#39;;function getCommentTotal() {
    return 100;
}class Comment { }namespace MessageBoard;const PATH = &#39;/message_board&#39;;function getCommentTotal() {
    return 300;
}class Comment { }//调用当前空间的常量、函数和类echo PATH; ///message_boardecho getCommentTotal(); //300$comment = new Comment();//调用Article空间的常量、函数和类echo \Article\PATH; ///articleecho \Article\getCommentTotal(); //100$article_comment = new \Article\Comment();?>

Then I did get the element data of the Article space.

Subspace
The calling syntax of namespace is like a file path, which makes sense. It allows us to customize subspaces to describe the relationship between each space.

Sorry, I forgot to mention that the two modules article and message board are actually in the same blog project. If you use namespace to express their relationship, it is like this:
Copy the code as follows:

<?php//我用这样的命名空间表示处于blog下的article模块namespace Blog\Article;class Comment { }//我用这样的命名空间表示处于blog下的message board模块namespace Blog\MessageBoard;class Comment { }//调用当前空间的类$comment = new Comment();//调用Blog\Article空间的类$article_comment = new \Blog\Article\Comment();?>

Moreover, subspaces can also define many levels, such as Blog\Article\Archives\Date

Public Space
I have a common_inc.php script file, which contains some useful functions and classes:
Copy the code as follows:

<?phpfunction getIP() { }class FilterXSS { }?>

Introduce this script in a namespace , elements in the script will not belong to this namespace. If there are no other namespaces defined in this script, its elements will always be in the public space:
Copy the code as follows:

<?phpnamespace Blog\Article;//引入脚本文件include &#39;./common_inc.php&#39;;$filter_XSS = new FilterXSS(); //出现致命错误:找不到Blog\Article\FilterXSS类$filter_XSS = new \FilterXSS(); //正确?>

The way to call the public space is to add \ directly before the element name. Otherwise, the PHP parser will think that I want to call the element under the current space. In addition to custom elements, it also includes PHP's own elements, which all belong to the public space.

I want to mention that in fact, public space functions and constants can be called normally without adding \ (I don’t understand why PHP does this), but in order to correctly distinguish elements, it is recommended to add \# when calling functions.

##Name terminology

Before talking about aliases and imports, you need to know the terms for the three names of spaces and how PHP parses them. The official documentation is very good, so I just used it.

1. Unqualified name, or class name without prefix, such as $comment = new Comment();. If the current namespace is Blog\Article, Comment will be parsed as Blog\Article\Comment. If the code using Comment does not contain code in any namespace (in the global space), the Comment will be parsed as a Comment.

2.限定名称,或包含前缀的名称,例如 $comment = new Article\Comment();。如果当前的命名空间是Blog,则Comment会被解析为Blog\Article\Comment。如果使用Comment的代码不包含在任何命名空间中的代码(全局空间中),则Comment会被解析为Comment。

3.完全限定名称,或包含了全局前缀操作符的名称,例如 $comment = new \Article\Comment();。在这种情况下,Comment总是被解析为代码中的文字名(literal name)Article\Comment。

其实可以把这三种名称类比为文件名(例如 comment.php)、相对路径名(例如 ./article/comment.php)、绝对路径名(例如 /blog/article/comment.php),这样可能会更容易理解。

我用了几个示例来表示它们:
复制代码代码如下:

<?php//创建空间Blognamespace Blog;class Comment { }//非限定名称,表示当前Blog空间//这个调用将被解析成 Blog\Comment();$blog_comment = new Comment();//限定名称,表示相对于Blog空间//这个调用将被解析成 Blog\Article\Comment();$article_comment = new Article\Comment(); //类前面没有反斜杆\//完全限定名称,表示绝对于Blog空间//这个调用将被解析成 Blog\Comment();$article_comment = new \Blog\Comment(); //类前面有反斜杆\//完全限定名称,表示绝对于Blog空间//这个调用将被解析成 Blog\Article\Comment();$article_comment = new \Blog\Article\Comment(); //类前面有反斜杆\//创建Blog的子空间Articlenamespace Blog\Article;class Comment { }?>

其实之前我就一直在使用非限定名称和完全限定名称,现在它们终于可以叫出它们的名称了。

别名和导入
别名和导入可以看作是调用命名空间元素的一种快捷方式。PHP并不支持导入函数或常量。

它们都是通过使用use操作符来实现:
复制代码代码如下:

<?phpnamespace Blog\Article;class Comment { }//创建一个BBS空间(我有打算开个论坛)namespace BBS;//导入一个命名空间use Blog\Article;//导入命名空间后可使用限定名称调用元素$article_comment = new Article\Comment();//为命名空间使用别名use Blog\Article as Arte;//使用别名代替空间名$article_comment = new Arte\Comment();//导入一个类use Blog\Article\Comment;//导入类后可使用非限定名称调用元素$article_comment = new Comment();//为类使用别名use Blog\Article\Comment as Comt;//使用别名代替空间名$article_comment = new Comt();?>

我注意到,如果导入元素的时候,当前空间有相同的名字元素将会怎样?显然结果会发生致命错误。

例:
复制代码代码如下:

<?phpnamespace Blog\Article;class Comment { }namespace BBS;class Comment { }Class Comt { }//导入一个类use Blog\Article\Comment;$article_comment = new Comment(); //与当前空间的Comment发生冲突,程序产生致命错误//为类使用别名use Blog\Article\Comment as Comt;$article_comment = new Comt(); //与当前空间的Comt发生冲突,程序产生致命错误?>

动态调用
PHP提供了namespace关键字和NAMESPACE魔法常量动态的访问元素,NAMESPACE可以通过组合字符串的形式来动态访问:
复制代码代码如下:

<?phpnamespace Blog\Article;const PATH = &#39;/Blog/article&#39;;class Comment { }//namespace关键字表示当前空间echo namespace\PATH; ///Blog/article$comment = new namespace\Comment();//魔法常量__NAMESPACE__的值是当前空间名称echo __NAMESPACE__; //Blog\Article//可以组合成字符串并调用$comment_class_name = __NAMESPACE__ . &#39;\Comment&#39;;$comment = new $comment_class_name();?>

字符串形式调用问题

上面的动态调用的例子中,我们看到了字符串形式的动态调用方式,如果要使用这种方式要注意两个问题。

  1. 使用双引号的时候特殊字符可能被转义
    复制代码代码如下:

<?phpnamespace Blog\Article;class name { }//我是想调用Blog\Article\name$class_name = __NAMESPACE__ . "\name"; //但是\n将被转义为换行符$name = new $class_name(); //发生致命错误?>
  1. 不会认为是限定名称

PHP在编译脚本的时候就确定了元素所在的空间,以及导入的情况。而在解析脚本时字符串形式调用只能认为是非限定名称和完全限定名称,而永远不可能是限定名称。
复制代码代码如下:

<?phpnamespace Blog;//导入Common类use Blog\Article\Common;//我想使用非限定名称调用Blog\Article\Common$common_class_name = &#39;Common&#39;;//实际会被当作非限定名称,也就表示当前空间的Common类,但我当前类没有创建Common类$common = new $common_class_name(); //发生致命错误:Common类不存在//我想使用限定名称调用Blog\Article\Common$common_class_name = &#39;Article\Common&#39;;//实际会被当作完全限定名称,也就表示Article空间下的Common类,但我下面只定义了Blog\Article空间而不是Article空间$common = new $common_class_name(); //发生致命错误:Article\Common类不存在namespace Blog\Article;class Common { }?>

总结
我对PHP的命名空间刚刚接触,也不能随便给一些没有实践的建议。我个人认为命名空间的作用和功能都很强大,如果要写插件或者通用库的时候再也不用担心重名问题。不过如果项目进行到一定程度,要通过增加命名空间去解决重名问题,我觉得工作量不会比重构名字少。也不得不承认它的语法会对项目增加一定的复杂度,因此从项目一开始的时候就应该很好的规划它,并制定一个命名规范。

相关推荐:

PHP命名空间、性状与生成器详解

php命名空间用法详解

实例详解PHP命名空间用法

The above is the detailed content of Detailed usage of PHP namespace. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn