Skip to content

Instantly share code, notes, and snippets.

@junaidtk
Last active May 11, 2022 12:43
Show Gist options
  • Save junaidtk/4b8e8b91727b70ba55e5ebc05f84b384 to your computer and use it in GitHub Desktop.
Save junaidtk/4b8e8b91727b70ba55e5ebc05f84b384 to your computer and use it in GitHub Desktop.
PHP Namespace Concepts
While creating large applications, 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.
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.
Eg:
// class mail with name sapce SMTP
namespace SMTP;
class Mail{}
// class mail with name sapce SMTP
namespace Mailgun;
class Mail{}
// Usage of name space.
use SMTP\Mail as SMTPMail;
use Mailgun\Mailas MailgunMail;
$smtp_mailer = new SMTPMailer;
$mailgun_mailer = new MailgunMailer;
Example of defining Namespaces.
===================================
namespace MyProject1;
// PHP code for the MyProject1 namespace
namespace MyProject2;
// PHP code for the MyProject2 namespace
// Alternative syntax
namespace MyProject3 {
// PHP code for the MyProject3 namespace
}
Can define multiple namespace in a single file. one after another. But
I would strongly advise defining a single namespace per file.
Example file which contain namespace:
====================================
<?php
// application library 1
namespace App\Lib1;
const MYCONST = 'App\Lib1\MYCONST';
function MyFunction() {
return __FUNCTION__;
}
class MyClass {
static function WhoAmI() {
return __METHOD__;
}
}
?>
To call this code, we can use in PHP code.
<?php
header('Content-type: text/plain');
require_once('lib1.php');
echo \App\Lib1\MYCONST . "\n";
echo \App\Lib1\MyFunction() . "\n";
echo \App\Lib1\MyClass::WhoAmI() . "\n";
?>
Referece: https://www.sitepoint.com/php-namespaces-import-alias-resolution/
Namespace Importing
===================
<?php
use App\Lib2;
require_once('lib1.php');
require_once('lib2.php');
header('Content-type: text/plain');
echo Lib2\MYCONST . "\n";
echo Lib2\MyFunction() . "\n";
echo Lib2\MyClass::WhoAmI() . "\n";
?>
Alisaing Namespace
==================
use App\Lib1 as L;
use App\Lib2\MyClass as Obj;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment