无论是autoload(),还是spl_autoload_register(),相比于require或include,好处就是autoload机制是lazy loading,也即是并不是你一运行就给你调用所有的那些文件,而是只有你用到了哪个,比如说new了哪个文件以后,才会通过autoload机制去加载相应文件
在一些项目开发中需要用到单独的扩展类时,可以通过以下方法实现类的自动加载,可以遍历运行目录下的所有类
<?php
namespace AutoLoading;
/**
* 类的自动加载
* Class loading
* @package AutoLoading
*/
class loading {
public static function autoload($className)
{
/**
* API_ROOT换成你的应用运行路径
*/
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, API_ROOT .'\\'. $className).'.php';
if(is_file($fileName)){
require_once $fileName;
}
}
}
spl_autoload_register('\\AutoLoading\\loading::autoload');
?>
思路分析:
new \extend\PHPMailer\Lite,当系统中默认没有加载\extend\PHPMailer\Lite类时,spl_autoload_register会主动加载
/extend/PHPMailer/Lite.php
若文件存在,则加载成功,不存在则php会报一个类:"\extend\PHPMailer\Lite" 不存在的致命错误
无论从事什么行业,只要做好两件事就够了,一个是你的专业、一个是你的人品,专业决定了你的存在,人品决定了你的人脉,剩下的就是坚持,用善良專業和真诚赢取更多的信任。