DEV Community

Cover image for PHP Namespaces
Samuel K.M
Samuel K.M

Posted on

PHP Namespaces

Namespaces

PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants.

Namespaces:

  • Provide a way to better organize and group together classes according to functionality
  • They allow the same name to be used for more than one class

For example let say you have multiple folders in the root folder. Each of this folder has an index.php file that contains a certain login. As a concrete example, the file index.php can exist in both directory /home/bazeng and in /home/other, but two copies of index.php cannot co-exist in the same directory. In addition, to access the index.php file outside of the /home/bazeng directory, we must prepend the directory name to the file name using the directory separator to get /home/bazeng/index.php.

In the PHP world, namespaces are designed to solve two problems:

  • Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
  • Ability to alias (or shorten) Extra_Long_Names designed to alleviate the first problem, improving readability of source code.

Namespaces are declared at the top most section of a class. Namespace names are case-insensitive. For practical purpose create a folder called namespaces, inside create a folder called Car and create an index.php and copy the code below:

<?php
namespace Car;

class Sedan{
   public model;
   public function __construct($model){
     $this->model = $model
   }
   public function getModel(){
     echo $this-> model
   }
}
class Lorry{
   public model;
   public function __construct($model){
     $this->model = $model
   }
   public function getModel(){
     echo $this-> model
   }
}


Enter fullscreen mode Exit fullscreen mode

Go Back to the root folder namespaces and create an index.php file and copy this code:

<?php
namespace Car;
require "Car/index.php";
$sedan = new Sedan("Premio");
$lorry = new Lorry("Fuso");

$sedan->getModel();
echo "\n";
$lorry->getModel();

Enter fullscreen mode Exit fullscreen mode

Host in your local server and in your browser navigate to the namespaces folder i.e localhost/namespaces. You can also clone this repository.

It can be useful to give a namespace or class an alias to make it easier to write. This is done with the use keyword:

use Car as C;
$car = new C();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)