|
很多開(kāi)源系統(tǒng)如osCommerce框架中,都會(huì)在其源碼中找到use這個(gè)關(guān)鍵字,如osCommerce框架中就在index.php文件中出現(xiàn)了這段源碼:
use osCommerce/OM/Core/Autoloader;use osCommerce/OM/Core/OSCOM;
其實(shí),php的use關(guān)鍵字是自php5.3以上版本引入的。它的作用是給一個(gè)外部引用起別名。這是命名空間的一個(gè)重要特性,它同基于unix的文件系統(tǒng)的為文件或目錄創(chuàng)建連接標(biāo)志相類(lèi)似。
php命名空間支持三種別名方式(或者說(shuō)引用):
1、為一個(gè)類(lèi)取別名
2、為一個(gè)接口取別名
3、為一個(gè)命名空間取別名
這三種方式都是用 use 關(guān)鍵字來(lái)完成。下面是三種別名的分別舉例:
//Example #1 importing/aliasing with the use operator
<?phpnamespacefoo;useMy/Full/ClassnameasAnother;//thisisthesameasuseMy/Full/NSnameasNSnameuseMy/Full/NSname;//importingaglobalclassuseArrayObject;$obj=newnamespace/Another;//instantiatesobjectofclassfoo/Another$obj=newAnother;//instantiatesobjectofclassMy/Full/ClassnameNSname/subns/func();//callsfunctionMy/Full/NSname/subns/func$a=newArrayObject(array(1));//instantiatesobjectofclassArrayObject//withoutthe"useArrayObject"wewouldinstantiateanobjectofclassfoo/ArrayObject?>
注意的一點(diǎn)是,對(duì)于已命名的名字,全稱(chēng)就包含了分隔符,比如 Foo/Bar,而不能用FooBar,而“/Foo/Bar”這個(gè)頭部的"/"是沒(méi)必要的,也不建議這樣寫(xiě)。引入名必須是全稱(chēng),并且跟當(dāng)前命名空間沒(méi)有程序上的關(guān)聯(lián)。
php也可以在同一行上申明多個(gè),等同于上面的寫(xiě)法
<?phpuseMy/Full/ClassnameasAnother,My/Full/NSname;$obj=newAnother;//instantiatesobjectofclassMy/Full/ClassnameNSname/subns/func();//callsfunctionMy/Full/NSname/subns/func?>
還有值得一說(shuō)的是,引入是在編譯時(shí)執(zhí)行的,因此,別名不會(huì)影響動(dòng)態(tài)類(lèi),例如:
<?phpuseMy/Full/ClassnameasAnother,My/Full/NSname;$obj=newAnother;//instantiatesobjectofclassMy/Full/Classname$a = 'Another';$obj = New $a; // instantiates object of class Another?>
這里由于給變量$a 賦值了 'Another',編譯的時(shí)候,就將$a 定位到 Classname 了。
更詳細(xì)的用法讀者可以查閱php手冊(cè)或關(guān)注本站后續(xù)相關(guān)文章。
php技術(shù):PHP中的use關(guān)鍵字概述,轉(zhuǎn)載需保留來(lái)源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。