在一个命名空间里引入这个脚本,脚本里的元素不会归属到这个命名空间。如果这个脚本里没有定义其它命名空间,它的元素就始终处于公共空间中: 复制代码 代码如下: ?phpnamespace Blog/Article;//引入脚本文件 include './common_inc.php';$filter_XSS = new FilterXSS(); //出现致命错误:找不到Blog/Article/FilterXSS类$filter_XSS = new /FilterXSS(); //正确?
2.限定名称,或包含前缀的名称,例如 $comment = new Article/Comment();。如果当前的命名空间是Blog,则Comment会被解析为Blog/Article/Comment。如果使用Comment的代码不包含在任何命名空间中的代码(全局空间中),则Comment会被解析为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发生冲突,程序产生致命错误?