What are PHP Namespaces?
What are Namespaces in general?
A Layman answer with an example would be great.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Namespacing does for functions and classes what scope does for variables. It allows you to use the same function or class name in different parts of the same program without causing a name collision.
In simple terms, think of a namespace as a person’s surname. If there are two people named “John” you can use their surnames to tell them apart.
The Scenario
Suppose you write an application that uses a function named
output(). Youroutput()function takes all of the HTML code on your page and sends it to the user.Later on your application gets bigger and you want to add new features. You add a library that allows you to generate RSS feeds. This library also uses a function named
output()to output the final feed.When you call
output(), how does PHP know whether to use youroutput()function or the RSS library’soutput()function? It doesn’t. Unless you’re using namespaces.Example
How do we solve having two
output()functions? Simple. We stick eachoutput()function in its own namespace.That would look something like this:
Later when we want to use the different functions, we’d use:
Or we can declare that we’re in one of the namespaces and then we can just call that namespace’s
output():No Namespaces?
If we didn’t have namespaces we’d have to (potentially) change a lot of code any time we added a library, or come up with tedious prefixes to make our function names unique. With namespaces, we can avoid the headache of naming collisions when mixing third-party code with our own projects.