As shown in Declaring Namespaces, we can define a class in a namespace as follows:
namespace MyProject\\Shapes;
class Rectangle { ... }
To reference this class the full path (including the namespace) needs to be used:
$rectangle = new MyProject\\Shapes\\Rectangle();
This can be shortened by importing the class via the use
-statement:
// Rectangle becomes an alias to MyProject\\Shapes\\Rectangle
use MyProject\\Shapes\\Rectangle;
$rectangle = new Rectangle();
As for PHP 7.0 you can group various use
-statements in one single statement using brackets:
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();
Sometimes two classes have the same name. This is not a problem if they are in a different namespace, but it could become a problem when attempting to import them with the use
-statement:
use MyProject\\Shapes\\Oval;
use MyProject\\Languages\\Oval; // Apparantly Oval is also a language!
// Error!
This can be solved by defining a name for the alias yourself using the as
keyword:
use MyProject\\Shapes\\Oval as OvalShape;
use MyProject\\Languages\\Oval as OvalLanguage;
To reference a class outside the current namespace, it has to be escaped with a \\\\
, otherwise a relative namespace path is assumed from the current namespace:
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();