How to use Namespaces in PHP?

Hello friends, in today’s post, you have been told about PHP Namespaces, what happens, how it works, so let’s start.

Introduction to PHP Namespaces

In PHP, namespaces are used to bind different types of elements together. Also, it is also useful to use classes of the same name in the same project. As you know that you cannot use classes of the same name in your project. If you do this then errors will show. But if you keep these same name classes in different namespaces then you can avoid this problem.

You can store classes, interfaces and functions in a PHP namespace. If all these classes, interfaces and functions named classes, interfaces and functions are also in any other namespace, then there will be no error in your project. Because both are in different namespaces.

Defining Namespaces

The namespace keyword is used to declare namespaces in PHP. Whenever you declare a namespace in a file, you should put the namespace declaration at the top of the file.

<?php 
namespace myNamespace;
// Interfaces
// Classes
// Functions
?>

The classes you want to put in a namespace do not necessarily have to be in the same file. You can declare the namespace back at the top of the file in whichever file you want to put the content in that namespace. By doing this the content of that file will also come in the same namespace.

Sub Namespaces

Like any sub file directory, you can also create sub namespaces in PHP.

<?php 
namespace myNamespace/mySubNamespace;
// Interfaces
// Classes
// Functions
?>

Using PHP Namespaces

Any classes, interfaces and functions can be accessed by the name of the namespace. For this, you first write the name of the namespace, followed by (/) the name of the class, interface or function you want to use.

mynamespace.php

<?php 
// Declaring namespace
namespace myNamespace;
class myClass
{
public function display()
{
echo "<h2>This is from another namespace</h2>";
}
}
?>

mynamespace_2.php

<?php 
namespace newNamespace;
// Including other file
require "mynamespace.php";
// Accessing function of another namespace
$obj = new myNamespacemyClass;
$obj->display();
?>

In above example the object of myClass of namespace created in mynamespace.php file is created in mynamespace_2.php file. and its display function() is accessed. Both these namespaces can also be defined in the same file.