Saturday, June 6, 2009

PHP5 Namespaces

Namespaces are available in PHP as of PHP 5.3.0
A namespace is a container with classes, function and constants (also available in PHP>5.3.0), similar to the namespaces in C++/C# and packages in Java. As indicated in the official PHP documentation, namespaces help us to solve name collisions and use alias to call long name classes/functions.

definition syntax:
// no code or html allowed here ! ( except declare() )
namespace MyProject; // standard namespace

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }

//it's possibile to define another namespace in the same file
// however it's not a good idea
namespace MyProject2\Sub\Level; //namespace with hierarchy

//brackets are allowed
namespace MyProject3 {
//content.
}
?>

use of namespace:

print \CONSTANT;
print \class;
print \method();

where is the relative or absolute namespace path where constants, classes and methods will be searched first (e.g. MyProject2\Sub\Level).
Absolutes relative namespace paths must start with "\".
If no namespaces are specified, the constant, class or method will be searched in the current namespace (or file if the namespace is not declared).

use of aliases:
use My\Full\Classname as Another;
// instead of use "My\Full\Classname" as namespace, you can use "Another"


No comments:

Post a Comment

 

PHP and tips|PHP