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

本文介绍了三种PHP类的自动加载方法:使用spl_autoload_register注册自定义的自动加载器;使用__autoload函数实现自动加载;以及通过glob遍历指定目录加载类文件。每种方法都提供了详细的代码示例。

方式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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值