Namespacing In PHP

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 we write an application that uses a function named output(). Our output() function takes all of the HTML code on your page and sends it to the user.
Later on our application gets bigger and we want to add new features. We 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 your output() function or the RSS library's output() function? It doesn't. Unless you're using namespaces.

How do we solve having two output() functions? Simple. We stick each output() function in its own namespace.
That would look something like this:
    namespace MyProject;
    function output() {
        # Output HTML page
        echo 'HTML!';
    namespace RSSLibrary;
    function output(){
        # Output RSS feed
        echo 'RSS!';
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():
    namespace MyProject;
    output(); # Output HTML page
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.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>