If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
PHP में Namespace functions / classes / interface का collections होते हैं। जिसकी help से functions / classes / interface का एक group बनाकर use कर सकते हैं।
Actually namespace का मैं purpose code reusability में आने वाली problems को solve करना था -
re-usable code elements बनाते समय कई classes / functions का name same होने की वजह से naming confliction से बचाने के लिए।
classes / functions का हम एक alternative name रख सकते हैं , जिससे बड़े name होने से कोई problem भी नहीं होगी।
functions / classes / Interfaces की grouping करने की वजह से code - readability बढ़ी और file structure भी understandable हुआ।
PHP में namespace keyword का use namespaces को define करने के लिए किया जाता है , जो की किसी भी file का सबसे पहला statement होता है। और namespace को use करने के लिए use keyword का use किया जाता है।
/*function inside namespace*/ namespace MyNamespace; function myfun(){ echo 'HI'; } /*we can use it like this*/ myfun(); /*we can define same class name in diff - diff namespaces*/ namespace SMTP; class Mail{} namespace Mailgun; class Mail{} use SMTP\Mail as SMTPMail; use Mailgun\Mail as MailgunMail; /*we can use it like ths*/ $smtp_mailer = new SMTPMail; $mailgun_mailer = new MailgunMail;
ध्यान रहे Namespace define करने वाली हमेशा पहली लाइन ही होनी चाहिए otherwise Fatal Error generate होगी।
Fatal error: Namespace declaration statement has to be the very first statement or after any declare call in the script
File : php_namespace.php
<?php
namespace MyNamespace;
class MyClassFirstClass
{
public function sayhi()
{
echo 'Hi !';
}
}
/*now it's time to use them*/
use MyNamespace\MyClassFirstClass as MyClass;
$obj = new MyClass();
$obj->sayhi();
?>
Hi !
PHP में namespaces और namespace keyword case insensitive होते हैं। namespaces को हम ऐसे भी define कर सकते हैं।
namespace App and namespace app are same meaning. Besides, Namespace keword are case-insensitive. Namespace App namespace App and NAMESPACE App are same meaning.
आप एक ही file में multiple namespaces define कर सकते हैं।
File : php_namespace2.php
<?php
namespace MyProject {
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
}
namespace AnotherProject {
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
}
?>
Hi ! My name is Rahul Kumar Rajput. I'm a back end web developer and founder of learnhindituts.com. I live in Uttar Pradesh (UP), India and I love to talk about programming as well as writing technical tutorials and tips that can help to others.
Get connected with me. :) LinkedIn Twitter Instagram Facebook