spl_autoload_register实现类的自动加载


无论是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" 不存在的致命错误

鼎云博客
  • 最新评论
  • 总共0条评论