Namespaces in php
by Guna[ Edit ] 2014-04-04 14:42:36
Namespaces are introduced to avoid collisions in naming classes and functions in larger projects.
example,
Having two classes in same name leads to fatal error. In the same way, if you have functions with identical name in global space you run into issues.
So,to avoid these issues namespaces were introduced to organize our code in better way. In PHP, namespace concepts included from version 5.3
How namespace code lookalike?
namespace universe;
class earth{
function shout(){
echo 'shouting from universe<br>';
}
}
namespace another_universe;
function shout(){
echo 'shouting from another universe!!!<br>';
}
Usage,
$earth= new \universe\earth;
$earth->shout();
\another_universe\shout();
#with use keyword
use another_universe;
shout();
#aliasing
use \another_universe as au;
au\shout();
Outputs,
shouting from universe
shouting from another universe!!!
shouting from another universe!!!
shouting from another universe!!!
There are certain rules we've to follow while using namespaces,
# namespace declaration should be the first line of that file
# you may create any number namespaces in single file, but one per file should be ideal
# you may use curly braces for namespace to define blocks just like you use for classes
These are the basices, still some more things are there but you'll understand once you start using it.