自动加载类中spl_autoload_register()函数的用法

function ServerAutoload($className){
    $classFile = strtolower($className).'.php';
    $basedir = array();
    // 加载站点类
    $basedir[] = 'Web';
    // 加载Common相关类
    $basedir[] = 'Common';
    // 加载框架类
    $basedir[] = 'Framework';
    foreach ($basedir as $dir){
        findClassFile($dir,$classFile);
    }
}

function findClassFile($directory,$classFile){
    if(is_dir($directory)) {
        if ($dh = opendir($directory)) {
            while (($file = readdir($dh)) !== false) {
                if( (is_dir($directory.DIRECTORY_SEPARATOR.$file)) && $file != "." && $file != ".." ) {
                    findClassFile($directory.DIRECTORY_SEPARATOR.$file,$classFile);
                } else {
                    if( $file == $classFile ) {
                        require_once $directory.DIRECTORY_SEPARATOR.$classFile;
                        break;
                    }
                }
            }
            closedir($dh);
        }
    }
}


if (version_compare(PHP_VERSION, '5.1.2', '>=')) {
    //SPL autoloading was introduced in PHP 5.1.2
    if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
        spl_autoload_register('ServerAutoload', true, true);
    } else {
        spl_autoload_register('ServerAutoload');
    }
} else {
    /**
     * Fall back to traditional autoload for old PHP versions
     * @param string $classname The name of the class to load
     */
    function __autoload($classname)
    {
        ServerAutoload($classname);
    }
}
标签:

发表评论