很多開源系統如osCommerce框架中,都會在其源碼中找到use這個關鍵字,如osCommerce框架中就在index.php文件中出現了這段源碼:
1
2
|
use osCommerce\OM\Core\Autoloader; use osCommerce\OM\Core\OSCOM; |
其實,php的use關鍵字是自php5.3以上版本引入的。它的作用是給一個外部引用起別名。這是命名空間的一個重要特性,它同基于unix的文件系統的為文件或目錄創建連接標志相類似。
PHP命名空間支持三種別名方式(或者說引用):
1、為一個類取別名
2、為一個接口取別名
3、為一個命名空間取別名
這三種方式都是用 use 關鍵字來完成。下面是三種別名的分別舉例:
//Example #1 importing/aliasing with the use operator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<?php namespacefoo; useMy\Full\ClassnameasAnother; //thisisthesameasuseMy\Full\NSnameasNSname useMy\Full\NSname; //importingaglobalclass useArrayObject; $obj =newnamespace\Another; //instantiatesobjectofclassfoo\Another $obj =newAnother; //instantiatesobjectofclassMy\Full\Classname NSname\subns\func(); //callsfunctionMy\Full\NSname\subns\func $a =newArrayObject( array (1)); //instantiatesobjectofclassArrayObject //withoutthe"useArrayObject"wewouldinstantiateanobjectofclassfoo\ArrayObject ?> |
注意的一點是,對于已命名的名字,全稱就包含了分隔符,比如 Foo\Bar,而不能用FooBar,而“\Foo\Bar”這個頭部的"\"是沒必要的,也不建議這樣寫。引入名必須是全稱,并且跟當前命名空間沒有程序上的關聯。
PHP也可以在同一行上申明多個,等同于上面的寫法
1
2
3
4
5
6
|
<?php useMy\Full\ClassnameasAnother,My\Full\NSname; $obj =newAnother; //instantiatesobjectofclassMy\Full\Classname NSname\subns\func(); //callsfunctionMy\Full\NSname\subns\func ?> |
還有值得一說的是,引入是在編譯時執行的,因此,別名不會影響動態類,例如:
1
2
3
4
5
6
7
|
<?php useMy\Full\ClassnameasAnother,My\Full\NSname; $obj =newAnother; //instantiatesobjectofclassMy\Full\Classname $a = 'Another' ; $obj = New $a ; // instantiates object of class Another ?> |
這里由于給變量$a 賦值了 'Another',編譯的時候,就將$a 定位到 Classname 了。
更詳細的用法讀者可以查閱php手冊或關注本站后續相關文章。