What is namespace in PHP?

If you have same named function in functional programming, it’s not accepted but yes you can create same named function in different class. Now what about the class name? What if you have same named class in your application?

In this case we use namespace. Consider namespace as a virtual folder in your application. You cant create same named file in single directory but of course you can create same named file in different directories. namespace works in same logic.

Check this code and you will get idea.

File code: 3009.php

<?php

namespace OneName;

class Account
{
    public function __construct()
    {
        echo "I am 3009 object";
    }
}

File code 30092.php

<?php

class Account
{
    public function __construct()
    {
        echo "I am 30 09 2 object";
    }
}

Index file code:

<?php
include_once("3009.php");
include_once("30092.php");

use OneName\Account;    //if you remove this namespace here it will load the 30092 file and it's function
// so this is how Namespace works. You can create same named class but you defined it under various namespace ( that is same like virtual folder. 2 folders having same named directories but not one folder carry same named directories 2 times)

$obj1 = new Account();