命名空間中的三個名稱的術語如下所示:
1.非限定名稱,或不包含前綴的類名稱,例如 $comment = new Comment();。如果當前命名空間是Blog\Article,Comment將被解析爲Blog\Article\Comment。如果使用Comment的代碼不包含在任何命名空間中的代碼(全局空間中),則Comment會被解析爲Comment。
2.限定名稱,或包含前綴的名稱,例如 $comment = new Article\Comment();。如果當前的命名空間是Blog,則Comment會被解析爲Blog\Article\Comment。如果使用Comment的代碼不包含在任何命名空間中的代碼(全局空間中),則Comment會被解析爲Comment。
3.完全限定名稱,或包含了全局前綴操作符的名稱,例如 $comment = new \Article\Comment();。在這種情況下,Comment總是被解析爲代碼中的文字名(literal name)Article\Comment。
其實可以把這三種名稱類比爲文件名(例如 comment.php)、相對路徑名(例如 ./article/comment.php)、絕對路徑名(例如 /blog/article/comment.php),這樣可能會更容易理解。
在這裏創建一個Blog 空間,使用非限定名稱,表示當前Blog空間,實例化以後這個調用將被解析。使用限定名稱,表示相對於Blog空間,實例化以後這個調用將被解析成 Blog\Article\Comment(),注意類前面沒有反斜線。使用完全限定名稱,表示絕對於Blog空間,實例化以後這個調用將被解析,注意類前面有反斜線和沒有反斜線區別。
其示例代碼如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<?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
{ } ?> |