把这个类放到需要自动加载的文件里即可
<?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;