PHP Namespaces

PHP Namespace 7Design.Stduio Blog

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 Directory Flow
namespace directory 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.
?>

PHP Namespaces Multiple 7Design.Stduio Blog

Further reference about namespaces:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2018 7Design.Studio | Web Design, Web Application Development & UX Design | Chennai | India

Up ↑