Namespaces
| Why namespaces exist | |
| Declare a namespace | |
| Import with use | |
| Back to global with backslash |
Why namespaces exist
Two libraries can both define a class named Cart, and PHP allows each name only once. Namespaces put classes into named groups, so Acme carts and Beta carts coexist. The deep dive lives at Namespaces in PHP.
$a = new \Acme\Shop\Cart(); $b = new \Beta\Shop\Cart();
Declare a namespace
The namespace declaration must be the first statement in the file, and everything declared below it belongs to that group. One namespace per file keeps the mapping between files and names obvious.
namespace Shop; class Cart { public function total(): float { return 0.0; } }
Import with use
The use statement imports a class under its short name, so the code below reads cleanly. When two imports share a short name, the as keyword gives one of them an alias.
use Shop\Cart; use Shop\Order as CustomerOrder; $cart = new Cart(); $order = new CustomerOrder();
Back to global with backslash
A leading backslash escapes to the global space: \DateTime always means the built-in class, even inside a namespaced file. Remember that unqualified function calls fall back to global functions, while unqualified class names never do, so qualify shared classes explicitly.
namespace Shop; function make(): \DateTime { return new \DateTime("now"); }
Next: Composer and autoloading
Article author: Arthur Isaev