A PHP project, usually with only one portal file index.php, we typically write an auto-load function in this portal file to require the class file that will be instantiated later. Such as:
Spl_autoload_register (function ($className) {
Require ' class/'. $className. '. php ';
});
From the above code, we find that when loading automatically, we need to specify the folder where the class is stored in order to find the appropriate class. So the problem arises.
Before introducing a namespace:
Our project directory
index.php
controller.php
In index.php we need to instantiate a controller class in the Controller directory and invoke the model () method of the object, and this method needs to instantiate the model class in a model directory. Let's Run the index.php:
Warning: Require (controller/model.php): Failed to open stream:no such file or directory
Prompt does not have this file or directory. The reason is simple: PHP in the new Model (), is automatically to the controller directory down require, so can not find.
So what should our auto-load function do to solve the problem? Obviously, replacing ' controller/' with ' model/' or not writing directories will not load properly. As a result, the benefits of using namespaces are apparent.
After the namespace is introduced:
index.php
controller.php
model.php
We write namespaces for each class according to the structure of the file directory, and when we need to instantiate another class in one class, the IDE helps us write to the use namespace; 。 This way, when we write automatic loading, we don't have to think about which directory the class is going to load, just write:
Spl_autoload_register (function ($class) {
Require $class. '. php ';
});
Other classes of namespaces , so the auto-load function goes to the appropriate namespace to require other classes.
In this way, we will not worry about loading classes, greatly freeing up our programming burden.
"Finally understand" the benefits of PHP joining namespaces--Easy to load automatically