php 批量载入文件的几种方式

方式1:spl_autoload_register

// Register the autoloader.
/**
 * Contains the functionality for auto-loading service classes.
 */
class CFLoader
{
    /*%******************************************************************************************%*/
    // AUTO-LOADER

    /**
     * Automatically load classes that aren't included.
     *
     * @param string $class (Required) The classname to load.
     * @return boolean Whether or not the file was successfully loaded.
     */
    public static function autoloader($class)
    {
        $path = dirname(__FILE__) . DIRECTORY_SEPARATOR;

        // Amazon SDK classes
        if (strstr($class, 'Amazon'))
        {
            if (file_exists($require_this = $path . 'services' . DIRECTORY_SEPARATOR . str_ireplace('Amazon', '', strtolower($class)) . '.class.php'))
            {
                require_once $require_this;
                return true;
            }

            return false;
        }

        // Load CacheCore
        elseif (strstr($class, 'Cache'))
        {
            if (file_exists($require_this = $path . 'lib' . DIRECTORY_SEPARATOR . 'cachecore' . DIRECTORY_SEPARATOR . strtolower($class) . '.class.php'))
            {
                require_once $require_this;
                return true;
            }

            return false;
        }

        return false;
    }
}
spl_autoload_register(array('CFLoader', 'autoloader'));

方式2:__autoload

function __autoload($class_name) {
    //class directories
    $directorys = array(
        ROOT . '/Lib/',
        ROOT . '/Model/'
    );
    foreach ($directorys as $directory) {
        if (file_exists($directory . $class_name . '.class.php')) {
            require_once($directory . $class_name . '.class.php');
            return;
        }
    }
}

方式3:glob 非自动加载

$directorys = array(
    ROOT . '/Api/Lib/',
    ROOT . '/Web/lib/',
    ROOT . '/Web/lib/smarty/Smarty.class.php',
);
foreach ($directorys as $directory) {
    if(is_file($directory)){
        require_once($directory);
    }elseif(is_dir($directory)){
        foreach (glob($directory."*.class.php") as $filename) {
            if (file_exists($filename)) {
                require_once($filename);
            }
        }
    }
}
原文地址:https://www.cnblogs.com/wangxusummer/p/6409692.html