Sunday, March 13, 2011

Use that Namespaced Class

I've been spending a fair amount of time with php namespaces. So far experience has shown me that, it is much simpler to "use" classes explicitly, instead of namespaces.

A quick example:
use Namespace;
$obj = new Namespace\Class();
vs.
use Namespace\Class;
$obj = new Class();

Note that often you will use many more classes than one. Which would make "using" the namespace a one liner, and explicit use 5+ lines. However this has it's own advantages.

The Good:
  • You can see at a glance, in the top of a file, which dependencies it has.
  • You shorten class names even more, with no need for the namespace prefix.

The Bad:
  • The potential for name-clashes, but that is what aliasing is for, right?

It may seem like obvious advice, but I still did it the former way until I "got it".

No comments:

Post a Comment