今天看osCommerce源碼框架時index.php文件中用到了use這個關鍵字,
use osCommerce\OM\Core\Autoloader;
use osCommerce\OM\Core\OSCOM;
不是很清楚,特地翻了一下,use關鍵字是php5.3以上版本引入的
它的作用是給一個外部引用起別名。這是命名空間的一個重要特性,它同基於unix的文件系統的爲文件或目錄創建連接標誌相類似。
PHP命名空間支持三種別名方式(或者說引用):
1:爲一個類取別名
2:爲一個接口取別名
3:爲一個命名空間取別名
這三種方式都是用 use 關鍵字來完成。下面是三種別名的分別舉例:
//Example #1 importing/aliasing with the use operator
<?php
namespace foo;
use My\Full\Classname as Another;
// this is the same as use My\Full\NSname as NSname
use My\Full\NSname;
// importing a global class
use ArrayObject;
$obj = new namespace\Another; // instantiates object of class foo\Another
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
$a = new ArrayObject(array(1)); // instantiates object of class ArrayObject
// without the "use ArrayObject" we would instantiate an object of class foo\ArrayObject
?>
注意的一點是,對於已命名的名字,全稱就包含了分隔符,比如 Foo\Bar,而不能用FooBar,而“\Foo\Bar”這個頭部的"\"是沒必要的,也不建議這樣寫。引入名必須是全稱,並且跟當前命名空間沒有程序上的關聯。
PHP也可以在同一行上申明多個,等同於上面的寫法
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
?>
還有值得一說的是,引入是在編譯時執行的,因此,別名不會影響動態類,例如:
<?php
use My\Full\Classname as Another, My\Full\NSname;
$obj = new Another; // instantiates object of class My\Full\Classname
$a = 'Another';
$obj = New $a;
// instantiates object of class Another
?>
這裏由於給變量$a 賦值了 'Another',編譯的時候,就將$a 定位到 Classname 了。
文檔中還有更詳細的說明,篇幅有限,就說到這...
詳細參考:http://php.net/manual/en/language.namespaces.importing.php