A PHP project usually has only one entry file index.php. We usually write an automatic loading function in this entry file to require class files that will be instantiated in the future. For example:
<span style='font-family: "courier new", courier; font-size: 14px'>spl_autoload_register(function ($className) {</span><br><span style='font-family: "courier new", courier; font-size: 14px'> require 'class/' . $className . '.php';</span><br><span style='font-family: "courier new", courier; font-size: 14px'>});</span><br><br><span style='font-family: "Microsoft YaHei"; font-size: 14px'>通过以上的代码,我们发现:在自动加载时,我们需要指定存放类的文件夹,以便找到相应的类。那么问题产生了。</span><br><br><strong><span style="font-size: 18px; background-color: #339966">在引入命名空间之前:</span></strong>
Our project directory
index.php
##Controller.php
In index.php we need to instantiate a Controller class in the controller directory and call the model() method of this object, and this method needs to instantiate a Controller class in the model directory. Model class. Let’s run index.php:
Warning: require(controller/Model.php): failed to open stream: No such file or directory
Prompt that there is no such file or directory. The reason is very simple: when PHP uses new Model(), it automatically goes to the controller directory to require, so it cannot be found.
So, how should we write our automatic loading function to solve the problem? Obviously, changing 'controller/' to 'model/' or not writing the directory will not load properly. Therefore, the benefits of using namespaces emerge.
引入命名空间之后:
index.php
Controller.php
Model.php
We write the namespace for each class according to the file directory structure. When we need to instantiate another class in a class, the IDE will help us write it. use namespace ; . In this way, when we write automatic loading, we don’t need to consider which file directory the class to be loaded is in. We only need to write like this:
<span style='font-family: "courier new", courier; font-size: 14px'>spl_autoload_register(function ($class) {</span><br><span style='font-family: "courier new", courier; font-size: 14px'> require $class . '.php';</span><br><span style='font-family: "courier new", courier; font-size: 14px'>});</span><br><br><span style='font-family: "Microsoft YaHei"; font-size: 14px'>因为我们在index.php中use了所用到的类的命名空间,自动加载函数会到相应的命名空间中去寻找类(上述代码中的$class就相当于是'controller\Controller'),而这些类中又需要实例化其他的类,因为这些类中也声明了use <em>其他类的命名空间 </em>;,所以自动加载函数又会去相应的命名空间中去require其他类。</span><br><br><span style='font-size: 16px; font-family: "Microsoft YaHei"'>这样,我们就不会为加载类而发愁了,极大地解放了我们的编程负担。</span>
The above is the detailed content of Detailed explanation of PHP automatic loading examples. For more information, please follow other related articles on the PHP Chinese website!