PHP में Namespace functions / classes / interface का collections होते हैं। जिसकी help से functions / classes / interface का एक group बनाकर use कर सकते हैं।


Actually namespace का मैं purpose code reusability में आने वाली problems को solve करना था -

  1. re-usable code elements बनाते समय कई classes / functions का name same होने की वजह से naming confliction से बचाने के लिए।

  2. classes / functions का हम एक alternative name रख सकते हैं , जिससे बड़े name होने से कोई problem भी नहीं होगी।

  3. functions / classes / Interfaces की grouping करने की वजह से code - readability बढ़ी और file structure भी understandable हुआ।


PHP में namespace keyword का use namespaces को define करने के लिए किया जाता है , जो की किसी भी file का सबसे पहला statement होता है। और namespace को use करने के लिए use keyword का use किया जाता है।

PHP Namespace Syntax

/*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

PHP Namespace Example

File : php_namespace.php

Copy Fullscreen Close Fullscreen
<?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();
?>
Output
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.
Defining multiple namespaces in the same file

आप एक ही file में multiple namespaces define कर सकते हैं।

File : php_namespace2.php

Copy Fullscreen Close Fullscreen
<?php 
 namespace MyProject {
	const CONNECT_OK = 1;
	class Connection { /* ... */ }
	function connect() { /* ... */  }
 }

 namespace AnotherProject {
	const CONNECT_OK = 1;
	class Connection { /* ... */ }
	function connect() { /* ... */  }
 }
?>

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers