引用命名空间中的类或函数

声明命名空间所示,我们可以在命名空间中定义一个类,如下所示:

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();