What are namespaces good for?

ive created my own framework and alot of it is operated by a bunch of classes ive written. what im wondering is how can namespaces help me? is it really worth using it?


if you can please show me an example so that i can better understand thanks

It’s a very good question and I am kind of hoping someone can offer a useful answer.

Namespacing in general tries to protect against having two classes (or functions or constants) with the same name. However, because php was originally developed without namespace support, the problem was already solved by simply using longer class name. I can’t think of any useful third party library that doesn’t use a prefix to distinguish itself from other libraries.

Given that namespaces and prefixed class names both solve the same problem we should then investigate if namespaces offer some additional benefits.

Namespaces allow us to use shorter class names which can save a bit of typing and possibly make the code easier to maintain but, since only one namespace can be active at a time, they really only help if the classes you are using are all in the same namespace. When I am creating instances, I tend to create one from one namespace and then maybe another from a different namespace. So the shorter names really don’t do much for me.

Namespaces also allow you to generate aliases which again can shorten class names. But you can do pretty much the same thing by assigning class names to variables. So that seems to be wash.

So the bottom line is that I really have no idea what PHP namespaces are good for. On the other hand, a lot of really smart people spent a lot of time and effort to implement them. So I am kind of hoping one of them stops by and demonstrates how to use them effectively.