PHP中的use關鍵字概述_php技巧

來源:互聯網
上載者:User

很多開源系統如osCommerce架構中,都會在其源碼中找到use這個關鍵字,如osCommerce架構中就在index.php檔案中出現了這段源碼:

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

<?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?>

注意的一點是,對於已命名的名字,全稱就包含了分隔字元,比如 Foo\Bar,而不能用FooBar,而“\Foo\Bar”這個頭部的"\"是沒必要的,也不建議這樣寫。引入名必須是全稱,並且跟當前命名空間沒有程式上的關聯。

PHP也可以在同一行上申明多個,等同於上面的寫法

<?phpuseMy\Full\ClassnameasAnother,My\Full\NSname;$obj=newAnother;//instantiatesobjectofclassMy\Full\ClassnameNSname\subns\func();//callsfunctionMy\Full\NSname\subns\func?>

還有值得一說的是,引入是在編譯時間執行的,因此,別名不會影響動態類,例如:

<?phpuseMy\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手冊或關注本站後續相關文章。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.