
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
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.
- Related Articles
- PHP namespace keyword and __NAMESPACE__ constant
- PHP Defining namespace
- Final keyword in PHP
- What is a namespace in Python?
- PHP final Keyword
- What is global namespace pollution in JavaScript?
- What is the equivalent of C# namespace in Java?
- What is the use of Namespace and Accessors in Less?
- What is Keyword Streaming?
- What is volatile keyword in C++?
- What is "out" keyword in Kotlin?
- Extending namespace and Unnamed namespace
- Namespace in C++
- What is the yield keyword in JavaScript?
- What is the const Keyword in C++?
