Table of contents
Definition
Namespaces refer to the act of creating a scope within which a set of code operates.
Use Cases and Examples
Without namespaces, every part of your source code will have access to other unrelated parts. This means there is a chance for conflict within your codebase. For example, if you have the same variable name as there is in a third-party code you need for your application then there is a chance one of them will be overridden. By using namespaces to scope out different parts of your code you can partition your codebase and unrelated parts will have no access to each other unless explicitly accessed.
01: //Old payment class (start)
02: namespace OldWallet;
03:
04: class Payment {
05: public function pay() {
06:
07: }
08: }
09: //Old payment class (end)
10:
11: //New payment class (start)
12: namespace newWallet;
13:
14: class Payment {
15: public function pay() {
16:
17: }
18: }
19: //New payment class (end)
20:
21: //Invoking old walllet pay method
22: new oldWallet\Payment::pay();
23:
24: //Invoking new walllet pay method
25: new newWallet\Payment::pay();
From the above PHP code, we have two payment classes, both under different namespaces. As you can see although they both contain a Payment
class and even the same pay
method within the same stretch of code we can execute both of them without any conflicts by prefixing them with their namespaces oldWallet
and newWallet
respectively.
Summary
We don't always have to use namespaces within our code, however, for large projects, it's an indispensable part of the software.
Here is another article you might like 😊 What Are Statically Typed Languages?