PHP Namespaces

There are possible conflicts that we can encounter with two classes with the same name. Namespaces in php helps resolve that issue.

Following is an simple illustration of the use of Namespace in php.

Considering the following scenario, we have two files, app.php and project.php.

app.php::
<?php
     namespace App;
     Class Test{
         public static function checknamespace(){
             echo "App/Test";
         }
     }
?>
project.php::
<?php
    namespace Project;
    Class Test{
        public static function checknamespace(){
            echo "Project/Test";
        }
    }
?>

Now, if we would include app.php file to project.php to use function checknamespace of class Test of app.php by:

project.php::
<?php
    include 'app.php';
    use App/Test;
    namespace Project;
    Class Test{
        public static function checknamespace(){
            echo "Project/Test";
        }
    }
?>

This will create a conflict in compilation for having the same Class name “Test”. To resolve this, namespace provides the easy aliasing of the class name by using ‘as’ like in the following example:

project.php::
<?php
    include 'app.php';
    use App/Test as Ap;
    namespace Project;
    Class Test{
        public static function checknamespace(){
            echo "Project/Test";
        }
    }
    //Ap is an alias to the class Test in app.php, this will call the function 
    checknamespace() of app.php resulting the output of string "App/Test"
    Ap::checknamespace();
?>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s