Home > Backend Development > PHP Tutorial > In PHP, what does the 'namespace' keyword mean?

In PHP, what does the 'namespace' keyword mean?

PHPz
Release: 2023-09-07 21:26:02
forward
1163 people have browsed it

In PHP, what does the namespace keyword mean?

In this article, we will learn about namespaces in PHP. In PHP, when we create large applications or integrate third-party applications/libraries, there may be conflicts between class names, function names. Therefore, to avoid these problems, PHP "namespaces" provide a way to group related classes, interfaces, functions, and constants.

Let’s look at the following syntax for declaring a namespace.

Syntax
<?php
   namespace MyfirstNamspace {
      function welcome() {
         echo &#39;welcome To Namespace&#39;;
      }
   }
?>
Copy after login

In the PHP world, namespaces are designed to solve two problems that creators of libraries and applications encounter when making reusable code components, which are:

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

Note:

The namespace is designed to represent the address of the file in the application. Sometimes we may need to shorten the address, in this case, we can utilize the "USE" keyword as Alias ​​for this address. Let us 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;
?>
Copy after login

Explanation:

Here we get two classes with the same name, for example Mail has two different namespaces. If we want to use both Mail classes then we can use aliases. Later in your code if we want to access these class objects then we can implement them as well.

The above is the detailed content of In PHP, what does the 'namespace' keyword mean?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template