PHP命名空间(Namespace)的使用简介

时间:2023-03-08 23:37:03
PHP命名空间(Namespace)的使用简介

原文链接:https://www.cnblogs.com/zhouguowei/p/5200878.html

PHP命名空间(Namespace)的使用简介

可以导入命名空间也可以导入命名空间的类

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

注意:use不等于require_once或者include,use的前提是已经把文件包含进当前文件。https://www.cnblogs.com/jiqing9006/p/5406994.html

如果使用了use,下面再new的时候就可以用别名,不然就要new一个完整路径的类,就像tp5快速入门->基础->视图:

[ 新手须知 ]
这里使用了use来导入一个命名空间的类库,然后可以在当前文件中直接使用该别名而不需要使用完整的命名空间路径访问类库。也就说,如果没有使用 use think\Controller;
就必须使用 class Index extends \think\Controller
这种完整命名空间方式。

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

<?php
namespace Blog\Article;
class Comment{} //创建一个BBS空间
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 Blog\Article;
class Comment{
function aa(){
echo ;
}
} //创建一个BBS空间
namespace BBS;
class Comment{}
class Comt{} //导入一个类
//use Blog\Article\Comment;
$article_comment = new \Blog\Article\Comment();//正确//为类使用别名
//use Blog\Article\Comment as Comt;
$article_comment = new \Blog\Article\Comment();//正确
$article_comment->aa();//输出33
?>