user3618959
user3618959

Reputation:

Why Use Namespaces (PHP)

I'm not quite getting why one would need to use namespaces. Well, I've got some reasons from other people's questions but I'm not entirely sure if I understand it.

From my reading, it seems that the only reason to use namespaces is so that class names can be re-used for programs that have different modules? Is that correct?

eg) So if module "Lalaland" has a class named "pillows". I wouldn't be able to use a class named "pillows" in a different module called "Slumberland" if I were to load both modules? So the fix then would be to create a namespace Lalaland and a namespace Slumberland. Within those namespaces, I can then use class "pillows"? Did I get that right?

Upvotes: 2

Views: 345

Answers (2)

cujo
cujo

Reputation: 378

That is correct, it is used to prevent naming collisions, if we did not have this and loaded to libraries php would not know which class you are talking about. This would cause either errors or just overwrite the class which would break the modules. Namespaces save you having to edit every framework that has the same name as another you are using.

Upvotes: 1

birdspider
birdspider

Reputation: 3074

I would say the main uses are "organizing" and "naming"

many things may call for a parse method or function and instead of inventing a parserX_parse function or even (watch the classname) ParserX::parse

i.e. you could go with a namespace ParseLibA where a Parser has a parse method and a SpeedParseLib which does the same, without name-clashes

Upvotes: 1

Related Questions