自动加载vs在PHP中包含或要求 [英] autoload vs include or require in php

查看:91
本文介绍了自动加载vs在PHP中包含或要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在经历自动加载,我意识到自动加载可能与require或include相同,并且我得出的结论是,使用自动加载而不是require或include可能会有优势. 使用自动加载而不是require或include来在php文件中使用类的优点是什么?

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?

推荐答案

在处理文件时,可能必须要求其他文件位于顶部才能使用其功能.

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.

因此,自动加载文件.

例如,您可以将所有类保留在一个名为classes的文件夹下.然后制作一个引导文件,您可以在其中编写自动加载器:

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.

这篇关于自动加载vs在PHP中包含或要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆