How to use PHP Namespaces

How to use PHP Namespaces

Namespaces : The namespaces is basically the name of folder/directory[physical or virtual] in which you put all code that belong to specific group. For example you are wrting code for image gallary then it is better to put all code in one folder with name "image_gallery" so that when you create other image gallery then you can simply put in other folder so but you use same class name and file name.The other benefit is that if your code integrated with other code then it do not create any problem. This is very commonly used concept in CMS/Framework when you creating extension for the CMS/Framework. In other language like java it is called package. PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants. Here is an example of namespace syntax in PHP:

Note : Namespace are created at run time in php environment you may create multiple name space in one file as I have explanced in advanced example.

// ClassNamespace.php
use gallery\gallery1 as g1;
use gallery\gallery2 as g2;


require_once('gallery/gallery1/MyGallery.php');
require_once('gallery/gallery2/MyGallery.php');

$obj1 =  new g1\MyGallery();
echo "<br>",$obj1->getName();

$obj2 =  new g2\MyGallery();
echo "<br>",$obj2->getName();

// 1st require flie
//// gallery/gallery1/MyGallery.php
namespace gallery\gallery1;

class MyGallery 
{
 const NAME = 'This Gallery1 developed by Baljit Singh using PHP 7.';	

 function getName()
 {
  return self::NAME;
 } 
}


// 2nd require flie
// gallery/gallery2/MyGallery.php
namespace gallery\gallery2;

class MyGallery 
{
 const NAME = 'This Gallery2 developed by Baljit Singh using PHP 7.';	

 function getName()
 {
  return self::NAME;
 } 
	
}

Advanced namespace example

namespace gallery\gallery1;
//ClassNamespaceAdv.php
class MyGallery 
{
 const NAME = 'This Gallery1 developed by Baljit Singh using PHP 7.';	

 function getName()
 {
  return self::NAME;
 } 
}

namespace gallery\gallery2;

class MyGallery 
{
 const NAME = 'This Gallery2 developed by Baljit Singh using PHP 7.';	

 function getName()
 {
  return self::NAME;
 } 
	
}

use gallery\gallery1 as g1;
use gallery\gallery2 as g2;


$obj1 =  new g1\MyGallery();
echo "<br>",$obj1->getName();

$obj2 =  new g2\MyGallery();
echo "<br>",$obj2->getName();
Tags