What is "namespace" keyword in PHP?


In this article, we are going to learn about namespace in PHP. In PHP when we are creating large applications or when integrating third-party applications/library then there may be chances of collision between class names, function names. So to avoid these problems PHP "Namespaces" provide a way in which to group related classes, interfaces, functions and constants.

Let's see the syntax of declaring namespace below.

Syntax

<?php
   namespace MyfirstNamspace {
      function welcome() {
         echo 'welcome To Namespace';
      }
   }
?>

In the PHP world, namespaces are intended to take care of two issues that creators of libraries and applications experience when making re-usable code components, Those are:

  • 1.Name impact between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
  • 2.Ability to abbreviate Extra_Long_Names for improving the readability of source code.

Note:

A namespace is designed to represent the address of the file in an application, Sometime we may need to shorten the address, in that case, we can utilize the "USE" keyword for the alias to that address. Let's understand through an example.

<?php
   namespace SMTP;
      class Mail{}
   namespace Mailgun;
      class Mail{}
   use SMTP\Mail as SMTPMail;
   use Mailgun\Mailas MailgunMail;
   $smtp_mailer = new SMTPMailer;
   $mailgun_mailer = new MailgunMailer;
?>

Explanation:

Here we got two classes with the same name, as Mail with two different namespaces. And if we want to use both Mail classes at the same time then we can use an alias. Later in your code, if we want to access those class objects then also we can implement them.

Updated on: 31-Dec-2019

286 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements