Home  >  Article  >  Backend Development  >  Detailed explanation of PHP automatic loading examples

Detailed explanation of PHP automatic loading examples

零下一度
零下一度Original
2017-07-23 13:24:251636browse

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:

spl_autoload_register(function ($className) {
   require 'class/' . $className . '.php';
});

通过以上的代码,我们发现:在自动加载时,我们需要指定存放类的文件夹,以便找到相应的类。那么问题产生了。

在引入命名空间之前:

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:

spl_autoload_register(function ($class) {
   require $class . '.php';
});

因为我们在index.php中use了所用到的类的命名空间,自动加载函数会到相应的命名空间中去寻找类(上述代码中的$class就相当于是'controller\Controller'),而这些类中又需要实例化其他的类,因为这些类中也声明了use 其他类的命名空间 ;,所以自动加载函数又会去相应的命名空间中去require其他类。

这样,我们就不会为加载类而发愁了,极大地解放了我们的编程负担。

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn