Home  >  Article  >  Backend Development  >  PHP - detailed introduction to namespace usage

PHP - detailed introduction to namespace usage

王林
王林forward
2019-08-28 16:01:422164browse

Regarding the namespace, the official document has already explained it in detail [View]. I have made some practice and summary here.

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.

Basic:

Namespace divides the code into different spaces (areas), and the constants, functions, and classes of each space (for the sake of laziness, I They are called elements below) and their names have no influence on 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

The code is as follows:

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

It should be noted that there cannot be any code in front of the first namespace of the current script file , the following writing methods are all wrong:

The code is as follows:

//在脚本前面写了一些逻辑代码
<?php
$path = "/";
class Comment { }
namespace Article;
?>

or as follows:

//在脚本前面输出了一些字符
<html></html>
<?php
namespace Article;
?>

Why do we need 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:

The code is as follows:

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

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

Between different spaces You cannot directly call other elements. You need to use the namespace syntax:

The code is as follows:

<?php 
namespace 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 A syntax like a file path: \space name\element name

Except for classes, the usage of functions and constants is the same. Below I created new elements for the two spaces and placed them in the MessageBoard space. Their values ​​are output in .

The code is as follows:

<?php 
namespace 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_board
echo getCommentTotal(); //300
$comment = new Comment();
//调用Article空间的常量、函数和类
echo \Article\PATH; ///article
echo \Article\getCommentTotal(); //100
$article_comment = new \Article\Comment();
?>

Subspace:

The calling syntax of the namespace like the file path makes sense, it allows us to customize Subspaces are used to describe the relationships between spaces.

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

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

Public space

I have a common_inc.php script file, which has some useful functions And class:

<?php 
function getIP() { }
class FilterXSS { }
?>

Introducing this script in a namespace, the elements in the script will not belong to this namespace. If no other namespace is defined in this script, its elements will always be in the public space:

<?php 
namespace 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 directly add \ before the element name, otherwise the PHP parser will think I want to call the element under the current space. In addition to custom elements, there are also elements that come with PHP, which all belong to the public space.

I want to mention that in fact, the functions and constants in the public space 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 \

3 and name terms

when calling the function. 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 was very good, so I just used it.

1.非限定名称,或不包含前缀的类名称,例如 $comment = new Comment();。如果当前命名空间是Blog\Article,Comment将被解析为Blog\Article\Comment。如果使用Comment的代码不包含在任何命名空间中的代码(全局空间中),则Comment会被解析为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 
//创建空间Blog
namespace 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的子空间Article
namespace Blog\Article;
class Comment { }
?>

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

它们都是通过使用use操作符来实现

代码如下:

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

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

<?php 
namespace 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__可以通过组合字符串的形式来动态访问

<?php 
namespace 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、使用""时特殊字符可能被转义

<?php 
namespace Blog\Article;
class name { }
//我是想调用Blog\Article\name
$class_name = __NAMESPACE__ . "\name"; //但是\n将被转义为换行符
$name = new $class_name(); //发生致命错误
?>

2、不会认为是限定名称

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

<?php 
namespace 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视频教程

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

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete