Alike many other languages like Java and C++, PHP introduced Namespaces concept in version 5.3. PHP implementation of namespaces is somewhat similar to c++, because most of the syntax and design are borrowed from c++. So what namespaces holds new for you?

Need for namespace
 
          Large applications have more number of classes and functions, so there are chances that same name can be used for more than one function or class, which leads to name clashes.

          Also, there was a concern about issues raised due to overlapping function or class names in larger code bases. By using namespaces we can easily identify what functionality the code provides.

What is namespace?

          Namespace allows you to use the same function or class name in different part of same program / project without any name collision.

          Just assume you have three friends in the name of John, who are there with you in school, college, work respectively. How do you store their name & number in your mobile? Prefixing something as an identifier with their name? Like sch_john / col_john / wrk_john

          This helps us, to whom we are making calls and avoids name confusions. This is what namespace does for you.

Namespace code:

namespace.php


<?php
namespace purchase;
  function output(){
  echo 'Purchase output<br>';
  }
 
namespace sales;
  function output(){
    echo 'Sales output<br>';
  }
?>

There are certain rules in place to use namespace code:
  • Namespace names declared using keyword ‘namespace’
  • Namespace declaration should be the first line of  the file
  • Multiple namespaces in same file are permitted, but not recommended
  • Namespace blocks can be surrounded by curly braces, just like you use for classes
Using namespace code:

<?php
include_once ‘namespace.php’;
 
\purchase\output(); // Purchase output
\sales\output(); // Sales output
 
#or using alias
use \purchase as pr;
pr\output();
?>


It’s just the basic things i’ve discussed here, still there is lot more which I haven’t covered. You will better understand those concepts once you start using namespaces.
 


Comments (2)
Leave a Comment

loader Posting your comment...