Ever since PHP introduced namespaces in version 5.3, it has been possible to import classes under alias names. In my experience, developers only make use of this feature when forced to – i.e., to avoid name conflicts. I’d like to propose another potential use for them that I have found convenient once or twice: to improve naming.
Let’s say I am working with this JWT library, which has a
class with the rather generic looking name Builder
. Sure, its fully qualified name is
Lcobucci\JWT\Token\Builder
, which is much more clear, but that isn’t the name I use when
creating instances or typehinting. And in those places, I’d like something a little more
expressive than just Builder.
And this is where import aliasing comes into play: I can just write something like
<?php
import Lcobucci\JWT\Token\Builder as JwtBuilder;
// later
$jwtBuilder = new JwtBuilder();
And just like that, I’m no longer at the mercy of third-party vendors (or my colleagues – or myself for that matter) to choose good class names, because I can replace them with better ones. I have never seen anyone else do that, and it’s not something I do on a regular basis, either. But on the off-chance that I import a class with a name that just does not feel right when separated from its namespace, I am happy that PHP allows me to do it.