Namespaces is a method with which we can group variable,function or objects so that we can have more than one variable or function or object with same name .
Namespaces were introduced into PHP from version 5.3 onwards
Use
• Helps to prevent accidentally re-defining functions, classes, constants, …
• Avoids having to use long, highly descriptive class names
• Constants, classes, traits, interfaces and functions are affeced by the use of namespaces
• Create sub-namespaces to sub-divide a library
Declaring Namespaces
• Must declare the use of namespaces with the keyword “namespace” at the beginning of the code file (right after <?PHP)
• Use one namespace per code file (best practice)
• Unless a namespace is defined, constants, classes, functions, traits and interfaces are defined with the global namespace
• Within a namespace qualifying with a “\” references the global namespace
• Once code elements within a single namespace are defined, they can be used in other php files
Example
<?php namespace php; class php { public function phpcodez() { echo 'Function1 <br />'; } } namespace codez; class codez { public function phpcodez() { echo 'Function2 <br />'; } } $phpcodez = new phpphp(); $phpcodez->phpcodez(); $phpcodez = new codezcodez(); $phpcodez->phpcodez(); ?>