PHP namespace 命名空间

使用双引号的时候特殊字符可能被转义推荐这篇文章 :  请猛戳这里
小结:
(1)当前脚本文件的第一个命名空间前面不能有任何代码
(2)在不同空间之间不可以直接调用其它元素,需要使用命名空间的语法
(3)在一个命名空间里引入这个脚本,脚本里的元素不会归属到这个命名空间。如果这个脚本里没有定义其它命名空间,它的元素就始终处于公共空间中
(4)调用公共空间的方式是直接在元素名称前加 \  ,包括PHP自带的元素,都属于公共空间。
(5)PHP并不支持导入函数或常量
(6)使用双引号的时候特殊字符可能被转义

<?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 { }

?>

use引入命名空间

<?php
namespace Blog\Article;
class Comment
{
function method()
{
echo "using Blog\Article\method!";
}
}

//创建一个BBS空间
namespace BBS;
//导入一个命名空间
use Blog\Article;
//导入命名空间后可使用限定名称调用元素
//$article_comment = new Comment(); //错误,Class 'BBS\Comment' not found,非限定名称(理解为当前路径)
//$article_comment = new Blog\Article\Comment();//错误,Class 'BBS\Blog\Article\Comment' not found,限定名称(理解为相对路径)
//$article_comment = new \Article\Comment();//错误,Class 'Article\Comment' not found,完全限定名称(理解为绝对路径)

/*一下两行代码因为(理解为路径引用正确)因此运行成功*/
$article_comment1 = new \Blog\Article\Comment();//正确,完全限定名称,绝对路径
$article_comment2 = new Article\Comment();//正确,限定名称,相对路径
$article_comment3 = new BBS\Article\Comment();//错误,非限定名称,在当前命名空间中被解析为BBS\BBS\Article\Comment
$article_comment1->method();
$article_comment2->method();
?>


命名空间名称矛盾

<?php


namespace Blog\Article;

class Comment { }


namespace BBS;

class Comment { }

Class Comt { }


/*导入另外一个空间的类*/
//use Blog\Article\Comment;//与当前空间的Comment发生冲突【Cannot use Blog\Article\Comment as Comment because the name is already in use 】

/*为类使用别名*/
//use Blog\Article\Comment as Comt;//错误同上

?>

魔术变量_NAMESPACE_

<?php

namespace Blog\Article;

const PATH = '/Blog/article';

class Comment
{
function say()
{
echo "using Blog\Aritcle\Comment...";
}
}

echo namespace\PATH; //输出 /Blog/article,此时namespace代表当前命名空间
echo "<br>". __NAMESPACE__ ."<br>"; //输出Blog\Article
$comment1 = new namespace\Comment();
$comment1->say();

/*魔法常量__NAMESPACE__的值是当前空间名称*/

//可以组合成字符串实例化
$comment_class_name = __NAMESPACE__ . '\Comment';
$comment2 = new $comment_class_name();
$comment2->say();

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值