Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should i (not) use the "use" keyword for namespaces

Tags:

namespaces

php

I've been working with PHP 5.3 for more than a year now, and there's something I always do that I'm not sure is correct : whenever I use a class outside of the current context's namespace, is use the use keyword :

use Another\Class

so in the code I can write directly :

$object = new Class();

That's fine, but I often end up with a lot of use directives at the beginning of my files, and that's not so nice to maintain (if I don't use this class, I'm not likely to remove the use directive).

I could also write the whole namespace each time I use this class :

$object = new \Another\Class();

So I was wondering two things :

  • Is there any drawback of not using the use keyword (except the fact that you have to write the whole namespace each time), like things you can't do ?
  • Is there any drawback of using it ? (is it even slightly less performant because it somehow imports the class) ?

Edit Just to clarify : I know clean code is more important than small performance tweaks, I just like to know when the computer is working, I like to feel the efforts :-)

like image 229
Julien Avatar asked Jan 23 '13 07:01

Julien


1 Answers

The one big drawback to not using use, is the need to type out the full name every time.

The one big drawback to using it, is the possibility of name collisions with classes that are already defined. I'm not sure how PHP handles that, but either way you end up with a little extra hassle. The plus is that you don't actually have to use the same name...but then, the minus to that is that you have classes that don't correspond to filenames.

Before we even get into more of this performance BS, though: If you care about the performance cost of aliasing a freaking name, you're doing it wrong. Do not worry about "faster" syntax. Period. You, your users, and that guy compulsively clicking "Reload" with a stopwatch in hand, will not notice the difference. Ever. There are far better things to optimize, and that's assuming you've reached the point where you need to.

like image 54
cHao Avatar answered Oct 08 '22 00:10

cHao