[Finally understand] the benefits of adding PHP to a namespace-facilitate automatic loading and finally understand the namespace
A PHP project usually has only one entry file index. php. We usually write an automatic loading function in this entry file to the class file that will be instantiated by require later. For example:
Spl_autoload_register (function ($ className ){
Require 'class/'. $ className.'. php ';
});
Through the above Code, we found that when loading automatically, We need to specify a folder for storing classes to find the corresponding classes. The problem arises.
Before introducing a namespace:
Our project directory
Index. php
Controller. php
In index. php, We need to instantiate the controller class under the Controller directory and call the model () method of this object. This method needs to instantiate the model class under the Model directory. Run index. php:
Warning: Require (controller/Model. php): failed to open stream: No such file or directory
The system prompts that the file or directory does not exist. The reason is simple: PHP automatically goes to the controller directory for require in the new Model (), so it cannot be found.
So how can we write the auto-loaded function to solve the problem? Obviously, changing 'controller/'to 'model/' or not writing a directory cannot load normally. 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. When another class needs to be instantiated in one class, IDE will help us write the useNamespace;. In this way, when writing automatic loading, you don't have to consider which file directory the class to be loaded is in. You just need to write it like this:
Spl_autoload_register (function ($ class ){
Require $ class. '. php ';
});
Because we are in index. use the namespace of the classes used in php, the automatically loaded function searches for classes in the corresponding namespace ($ class in the above Code is equivalent to 'controller \ controller'), and other classes need to be instantiated in these classes, because these classes also declare the useNamespaces of other classes, So the automatically loaded function will go to the corresponding namespace to go to other require classes.
In this way, we will not worry about loading classes, which greatly frees our programming burden.