An important new feature in PHP 5.3 is namespaces.
This feature was proposed in PHP5.0x, but was later canceled and scheduled to be implemented in PHP6. And this time, PHP5.3 was released "ahead of schedule" again, which shows that developers attach great importance to it and are cautious.
When officially released, the content of the document may be out of date (documentation maybe out dated), so here is a brief explanation of the usage of the namespace: first, declare a namespace and add the new keyword namespace, which should be at the beginning of the class file
<?phpnamespace Project::Module;class User {const STATUS_OK = true;function register($data) {...}...} Then in the controller (maybe other files) you can call
$user = new
like thisProject::Module::User();$user->register($register_info); is indeed the same as usual, but we can connect two independent classes. For example,
Project::Module::User;Project::Module::Blog; This makes it easier to describe and understand the relationship between variables and classes from the language itself, thereby avoiding the "traditional" lengthy naming method of Project_Module_Blog .
The above description may be difficult to explain the benefits of using namespaces. The newly added use and as keywords may explain the problem better. The use and as statements can reference and declare namespace "aliases". For example, the code for instantiating the class in the above controller can be written like this:
use Project::Module;$user = new Module::User();$user->register($register_info); or even
use Project::Module:: User as ModuleUser;$user = new ModuleUser;$user->register($register_info);Constants in the class can also be accessed through the namespace. For example, STATUS_OK in the above class can be accessed through the namespace
Project::Module::User: :STATUS_OK access. Furthermore, you can also use aliases to simplify such long "variable names"
use Project::Module::User::STATUS_OK as STATUS_OK;echo STATUS_OK; By the way, the concept of "The Global Namespace". The so-called "hyperspace" refers to variables, classes and functions that do not have a designated namespace. For example
, a function like function foo() {...} can be executed using foo() or ::foo();.
Finally, use the autoload function to load the class in the specified namespace. The simple function is as follows
function __autoload( $classname ) {$classname = strtolower( $classname );$classname = str_replace( '::', DIRECTORY_SEPARATOR, $classname );require_once( dirname( __FILE__ ) . '/' . $classname . '.class.php' );} In this way, for example, calling
__autoload('Project::Module::User'); can automatically load the Project_Module_User.class.php file (although this seems inconvenient).