autoload vs include or require in php

為{幸葍}努か 提交于 2019-12-25 09:16:21

问题


I am currently going through autoloading and l realize that autoloading may just be the same with require or include and I have come to the conclusion that perhaps there could be an advantage for using autoloading instead of require or include. What is the advantage of using autoload instead of require or include to use a class in a php file?


回答1:


When you are working in a file, you might have to require in other files at the top in order to use their functionalities.

Depending on the requirement, that list can get very long. And doing this in every file is tedious,unclean and can be avoided.

Hence, autoload your files.

For example, you can keep all your classes under one folder named classes. Then make a bootstrap file where you can write the autoloader:

spl_autoload_register(function ($class) {
    require_once 'classes/' . $class . '.php';
});  

To make this work, all you have to do is keep the file name and class name the same.

Henceforth you need to require only this bootstrap file and all your classes will be autoloaded.



来源:https://stackoverflow.com/questions/39571248/autoload-vs-include-or-require-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!