很早以前闲着没事好玩写了个php自动加载的类,仅供参考

把这个类放到需要自动加载的文件里即可


<?php

/*
 *高级自动加载类
 *@author:jj
 *@date:2014-08-01
 *
 * **/

class AutoLoader_advance
{
    public static $sel;
    public $path;

    private function __construct($classPath)
    {
        $newstr = null;
        if ($classPath == null) {
            $newstr = str_replace("\\", "/", dirname(__FILE__) . "/"); //获取项目根路径转换"\"
        } else {
            if (is_dir($classPath)) {
                $newstr = str_replace("\\", "/", $classPath . "/"); //获取项目根路径转换"\"
            }
        }

        $this->path = $newstr;
        spl_autoload_register(array($this, 'autoload')); //注册函数
    }

    /**
     * @method:autoload(自动加载主函数)
     * @paramet:className(自动检测类名)
     *
     * */
    public function autoload($className)
    {
        $flg = false;
        $classpath = null;
        $file = null;
        $source = get_filetree($this->path); //迭代文件树
        $fileNameArr = $this->iterator($source); //迭代出所有文件名
        $file = $className . ".php";
        for ($i = 0; $i < count($fileNameArr); $i++) {
            if ($fileNameArr[$i] == $file && file_exists($source[$i])) {
                require_once $source[$i];
                $flg = true;
            }
        }
        if (!$flg) {
            die($file . "没有找到或该类不存在");
        }
    }

    /**
     * @method:iterator(迭代器)
     * @param:文件树数组源
     *
     **/
    public function iterator($array)
    {
        $fileNames = array();
        if (!is_array($array)) {
            die("文件树不是一个有效的数组");
        }
        for ($i = 0; $i < count($array); $i++) {
            $start = strripos($array[$i], "/");
            $fileNames[] = substr($array[$i], $start + 1);
        }
        return $fileNames;
    }

    /**
     * @method:run
     * @param:classpath(项目的绝对根路径)
     *
     * */
    public static function run($classPath = null)
    {
        if (!(self::$sel instanceof self)) {
            self::$sel = new self($classPath);
        }
        return self::$sel;
    }
}

/*
 * 遍历指定路径中的所有文件
 * **/
function get_filetree($path)
{
    $tree = array();
    foreach (glob($path . '/*') as $single) {
        if (is_dir($single)) {
            $tree = array_merge($tree, get_filetree($single));
        } else {
            $tree[] = $single;
        }
    }
    return $tree;

}


//使用


AutoLoader_advance::run(__DIR__);

$aaa = new AAA();
$message = $aaa->sayHello("你好");
echo $message;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值