在一個命名空間里引入這個腳本,腳本里的元素不會歸屬到這個命名空間。如果這個腳本里沒有定義其它命名空間,它的元素就始終處于公共空間中: 復制代碼 代碼如下: ?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發生沖突,程序產生致命錯誤?