Referencing a class or function in a namespace

suggest change

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Namespaces:
* Referencing a class or function in a namespace

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
22 Namespaces
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR