引用名稱空間中的類或函式
如宣告名稱空間所示,我們可以在名稱空間中定義一個類,如下所示:
namespace MyProject\Shapes;
class Rectangle { ... }
要引用此類,需要使用完整路徑(包括名稱空間):
$rectangle = new MyProject\Shapes\Rectangle();
這可以通過 use
語句匯入類來縮短:
// Rectangle becomes an alias to MyProject\Shapes\Rectangle
use MyProject\Shapes\Rectangle;
$rectangle = new Rectangle();
對於 PHP 7.0,你可以使用括號在一個語句中對各種 use
語句進行分組:
use MyProject\Shapes\{
Rectangle, //Same as `use MyProject\Shapes\Rectangle`
Circle, //Same as `use MyProject\Shapes\Circle`
Triangle, //Same as `use MyProject\Shapes\Triangle`
Polygon\FiveSides, //You can also import sub-namespaces
Polygon\SixSides //In a grouped `use`-statement
};
$rectangle = new Rectangle();
有時兩個類具有相同的名稱。如果它們位於不同的名稱空間中,這不是問題,但在嘗試使用 use
語句匯入它們時可能會出現問題:
use MyProject\Shapes\Oval;
use MyProject\Languages\Oval; // Apparantly Oval is also a language!
// Error!
這可以通過使用 as
關鍵字自己定義別名來解決:
use MyProject\Shapes\Oval as OvalShape;
use MyProject\Languages\Oval as OvalLanguage;
要引用當前名稱空間之外的類,必須使用\
對其進行轉義,否則將從當前名稱空間中假定相對名稱空間路徑:
namespace MyProject\Shapes;
// References MyProject\Shapes\Rectangle. Correct!
$a = new Rectangle();
// References MyProject\Shapes\Rectangle. Correct, but unneeded!
$a = new \MyProject\Shapes\Rectangle();
// References MyProject\Shapes\MyProject\Shapes\Rectangle. Incorrect!
$a = new MyProject\Shapes\Rectangle();
// Referencing StdClass from within a namespace requires a \ prefix
// since it is not defined in a namespace, meaning it is global.
// References StdClass. Correct!
$a = new \StdClass();
// References MyProject\Shapes\StdClass. Incorrect!
$a = new StdClass();