Why use PHP Namespace?

PHP Namespace is a virtual directory you create in PHP. It is used to avoid conflicts when declaring Classes in PHP.

In Object-Oriented Programming, it is best practice to place one class in one file, if there are 2 classes in 1 file then that just defeats the purpose of OOP. So why use Namespace? Here is an example.

In the index.php file, we have the code that:

  1. Requires 2 PHP files
  2. Instantiates the class A
require('first-class.php');
require('second-class.php');
$object = new A;

In first-class.php, we have a class and a method that displays a text.

class A{
    public function __construct(){
        echo "I am the first class A.";
    }
}

In our second file, second-class.php, we have a class with the same name.

class A{
    public function __construct(){
        echo "I am the second class A.";
    }
}

Now if we run the index.php file, we will get an error.

Fatal error: Cannot declare class A, because the name is already in use in C:\xampp\htdocs\php_tester\namespace\second_class.php on line 2

What happened is that the instance variable object is confused on which Class to instantiate. To solve this is to use namespace. This is important especially on huge projects and projects that use libraries. Namespace can also help collaborative projects for teams who code on a single project.

To use a namespace is simple. We add the namespace code at the top of the class and specify a name for it. In first-class.php file, we update the code to:

namespace FirstA;
class A{
    public function display_text(){
        echo "I am the first class A.";
    }
}

Now in our code in index.php, when we want to access the methods and properties under the first-class.php file, we update the following code to:

require('first-class.php');
require('second-class.php');
$object = new FirstA\A; //qualified class name

//result "I am the first class"

The code $object = new FirstA\A; is called the Qualified Class Name.

We can also place a namespace in our index.php file.

namespace FirstA;
require('first-class.php');
require('second-class.php');
$object = new A; //unqualified class name

//result "I am the first class"

Notice that I removed the namespace in the instantiation, we can call it as Unqualified Class Name.

But… how do we call the class under second-class.php? We do it by:

namespace FirstA;
require('first-class.php');
require('second-class.php');
$object = new A; //unqualified class name
echo "<br />"
$object = new /A; //fully qualified class name

We call it Fully Qualified Class name or FQCN.

We can also use the code “use“.

//namespace FirstA;
require('first-class.php');
require('second-class.php');

use FirstA\A as NewA

$object = new NewA; //unqualified class name
echo "<br />"
$object = new /A; //fully qualified class name

Leave a Reply

Your email address will not be published. Required fields are marked *