What is the use of namespace in php

php

Posted on 06 Aug 15 by Vickey
  580



The word 'namespace' come in PHP version 5.3 by using namespace we can define more than one classes with the same name.If we have two or more class with the same name for example if we have a third party class which we are using in our project and we have also a core class with the same name then
when we create the object of class it will return a fatal error 'Fatal error: Cannot redeclare class'

class Login
{
    public function do_login()
    {
        return 'I am login as admin';
    }
}

class Login
{
    public function do_login()
    {
        return 'I am login as User';
    }
}

class Login
{
    public function do_login()
    {
        return 'Login By Facebook';
    }
}

$myobj = new Login();
echo $myobj->do_login();

But we can fix this error by using namespace. we will create a different namespace for each class

namespace Myproject\Admin;
class Login
{
    public function do_login()
    {
        return 'I am login as admin';
    }
}


namespace Myproject\User;
class Login
{
    public function do_login()
    {
        return 'I am login as User';
    }
}



namespace Myproject\FacebookLogin;
class Login
{
    public function do_login()
    {
        return 'Login By Facebook';
    }
}

$myobj = new Login();
echo $myobj->do_login();

now it will not give error but it will use the last class and you will see it will print 'Login By Facebook' but if want to use the all classes then there is need to use namespace
in this case we will create class object by using name space

$myobj = new \Myproject\Admin\Login();
echo $myobj->do_login();


$myobj = new \Myproject\User\Login();
echo $myobj->do_login();

$myobj = new \Myproject\FacebookLogin\Login();
echo $myobj->do_login();

or we can use this also

use Myproject\Admin\Login as admin_login;
$myobj = new admin_login();
echo $myobj->do_login();

 


If this post help you reduce time to develop, you can help me to maintain this website :)
www.000webhost.com