DEV Community

Ghulam Mujtaba
Ghulam Mujtaba

Posted on

What is namespace in PHP and it's use?

What is a Namespace?

A namespace is a way to group related classes, functions, and constants together, avoiding conflicts with other code.

Defining a Namespace

A namespace is defined using the namespace keyword followed by the namespace name.

namespace Core;
Enter fullscreen mode Exit fullscreen mode

Using the use Keyword

The use keyword is used to import classes, functions, and constants from other namespaces into the current namespace.

use PDO;
Enter fullscreen mode Exit fullscreen mode

This imports the PDO class from the global namespace into the current namespace (Core).

namespace Core;
use PDO;

class Database {
    public $connection;
    public $statement;

    public function __construct($config, $username = 'root', $password = '') {
        $dsn = 'mysql:' . http_build_query($config, '', ';');
        $this->connection = new PDO($dsn, $username, $password, [
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Without the use Keyword

Without the use keyword, you would have to use the fully qualified name of the PDO class, like this \PDO:

namespace Core;

class Database {
    public $connection;
    public $statement;

    public function __construct($config, $username = 'root', $password = '') {
        $dsn = 'mysql:' . http_build_query($config, '', ';');
        $this->connection = new \PDO($dsn, $username, $password, [
            \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Importing Namespaces

Namespaces can be imported using the use keyword, like this:

use Core\Database;
Enter fullscreen mode Exit fullscreen mode

This imports the Database class from the Core namespace into the current namespace.

When to Use Namespaces

Namespaces are useful when:

  • You want to avoid conflicts with other code.
  • You want to organize your code into logical groups.
  • You want to use classes, functions, and constants from other namespaces.
use Core\Database;

$db = new Database($config['database']);
Enter fullscreen mode Exit fullscreen mode

Autoloading Classes and Functions

You can automatically load classes and functions using the spl_autoload_register function. But first, you need to change the autoloader statement of last project spl_autoload_register(function ($class) { require base_path("Core/{$class}.php"); });

to this:

spl_autoload_register(function ($class) { 
    $class = str_replace('\\', DIRECTORY_SEPARATOR, $class); 
    require base_path("{$class}.php"); 
});
Enter fullscreen mode Exit fullscreen mode

The statement str_replace('\\', DIRECTORY_SEPARATOR, $class); tells that:

  • str_replace is a PHP function that replaces a string with another string.
  • The first argument ('\\', is the string to be replaced, which is the namespace separator (\).
  • The second argument DIRECTORY_SEPARATOR is the string that will replace the namespace separator. DIRECTORY_SEPARATOR is a PHP constant that represents the directory separator (either / or \, depending on the operating system).
  • The third argument $class is the string that contains the class name, which may include namespace separators (\).

I hope that you have clearly understood it.

Top comments (2)

Collapse
 
xwero profile image
david duymelinck • Edited

A great article!

I would added a section about composer, because that is the way autoloading is done in an organised way.

An example of loading classes and functions

{
     "autoload": {
        "psr-4": {"Acme\\": "src/"}
       "files": ["src/helpers.php"]
    }
}
Enter fullscreen mode Exit fullscreen mode

With the psr-4 key all classes in the src folder will be autoladed with Acme as the vendor namespace.
With the files key you can add files that only contain functions.

Collapse
 
zubairmohsin33 profile image
Zubair Mohsin

Good work!