use breaks the fundamental aspects of PHP namespaces. Avoid
Oh, you want to know why? Fine. Keep reading.
Let’s review the fundamental aspects of PHP namespaces as stated in the PHP Docs Namespace Overview:
namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements
So namespaces focus on re-usable code elements. Let’s look at the two problems:
- Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
- Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.
namespace solves problem #1.
use solves problem #2. But things can get circular.
use can introduce name collisions and confusion. Which respectively reintroduces problem #1 and is the opposite of improving readability.
Consider the following namespaces and classes:
1 2 3 4 5 6 7
1 2 3 4 5 6 7
Controller class with
1 2 3 4 5 6 7 8 9 10
Service class is created?
It may be straightfoward with the entire codebase in front of you. But consider a larger codebase. What if you refactored
output() into another class? It all depends on the
use statement. Meaning the code is tightly coupled with
Controller class without
1 2 3 4 5 6 7 8
No question on which
Service class is created and no coupling.
There are other problems with
use, such as dynamic naming. But you don’t need more convincing.
use breaks what namespaces solve.
Spend a few extra keystrokes typing absolute namespaces for code clarity and portability. Future developers will thank you.