A new and important feature of PHP 5.3 is the namespace (namespace).
This feature was presented at php5.0x Time and was subsequently canceled and arranged for implementation in PHP6. This time again "advance" to the PHP 5.3 release, visible developers to its attention and cautious attitude.
The content of the document may have expired (documentation maybe out dated) at the time of the official release, so here is a simple description of the use of namespaces: First, declare a namespace, add a new keyword namespace, which should be at the beginning of the class file
1
2
3
4
5
6 7 8
|
<?php
namespace Project::module;
Class User { Const STATUS_OK = true;
function Register ($data) {
... }
...
}
? > |
You can then call it in the controller (possibly other files)
1
2
|
$user = new Project::module::user ();
$user->register ($register _info); |
It's true and normal, but we can relate two separate classes. Like what
1
2
|
Project::module::user;
Project::module::blog; |
This makes it easier to describe and understand the relationships between variables and classes from the language itself, thus avoiding the lengthy naming of Project_module_blog on the "traditional" approach.
The instructions above may be difficult to illustrate the benefits of using namespaces, and the newly added use and as keywords may be a better illustration of the problem. The use and as statements can reference and declare "aliases" of namespaces. For example, the code that instantiates the class in the above controller can be written like this
1
2
3
|
Use Project::module;
$user = new Module::user ();
$user->register ($register _info); |
Even
1
2
3
|
Use Project::module::user as Moduleuser;
$user = new Moduleuser;
$user->register ($register _info); |
Constants in a class can also be accessed through namespaces, such as the STATUS_OK in the above class can be passed through namespaces
1
|
Project::module::user::status_ok |
Access. Further, you can also use aliases to simplify the long "variable name"
1
2
|
Use PROJECT::MODULE::USER::STATUS_OK as STATUS_OK;
Echo STATUS_OK; |
By the way, the concept of hyperspace (the Global Namespace) is mentioned. The so-called "hyperspace" is the variables, classes, and functions that do not specify namespaces. Like what
1
2
3
|
function foo () {
...
} |
This function can be performed using foo (), or you can use:: foo (); Executed in this way.
Finally, you can load the class with the specified namespace with the AutoLoad function. The simple functions are as follows
1
2
3
4
5
|
function __autoload ($classname) {
$classname = Strtolower ($classname);
$classname = Str_replace (':: ', Directory_separator, $classname);
Require_once (DirName (__file__). '/' . $classname. '. class.php ');
|
In this way, such as calling
1
|
__autoload (' Project::module::user '); |
You can automatically load the Project_Module_User.class.php file (although this may not seem convenient).