(5)PHP并不支持导入函数或常量
use引入命名空间<?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
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();
?>
魔术变量_NAMESPACE_<?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;//错误同上
?>
<?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();
?>