PHP Namespaces Explained

php namespace image
PHP NAMESPACES

Namespace benefits, avoiding name collision when we integrate from different resources like third party libraries & packages.

Define a namespace:

We define namespaces at the top of page with “namespace” keyword. No other codes allowed to place before “namespace” keyword – with one exception, “declare” keyword.

namespace Le\Product\Age;

How to use a namespace class:

Example file name item-list.php, first we need to include the library which contain namespace and Import the namespace with “use” keyword.

require 'src/Products/ShopByAge.php'; //include namespace file
use \Le\Product\Age\ShopByAge; //import namespace

Namespace Example / Directory Structure:

php namespace flow diagram
NAMESPACES FILE STRUCTURE

filename: src/Products/ShopByAge.php

<?php
   namespace Le\Product\Age; //Defining Namespaces
   class ShopByAge{
       public function ageOneToTwo(){
         return 'Age Between One to Two';
      }  
   }
?>

filename: item-list.php

<?php 
  require 'src/Products/ShopByAge.php'; //Namespace file
  use \Le\Product\Age\ShopByAge; //Import namespace
  $age = new ShopByAge(); //Call class from the context for the namespace
  echo $age->ageOneToTwo(); //Return, Age Between One to Two
?>

Aliasing: We can give the class a friendly name by using the “as” keyword. And majorly used to shorten, extra long name using this keyword.

<?php 
  require 'src/Products/ShopByAge.php'; //Namespace file
  use \Le\Product\Age\ShopByAge as ProAge; //Import namespace and alias with ProAge
  $age = new ProAge(); //Call class from the context for the namespace
  echo $age->ageOneToTwo(); //Return, Age Between One to Two
?>

Global space: We have to use backslash(\) in front of the class name in order to call a class from global space.

<?php
  $a = new \stdClass; // call global scope, PHP's generic empty class.
?>
multiple php namespace format
MULTIPLE NAMESPACE USAGE

Further reference about namespaces: