随手写的,后台发现用不上,放上来以后可能用的着
1 /** 2 * SPL自动加载类 3 */ 4 class AutoLoad 5 { 6 7 /** 8 * 类文件所在目录 9 * 10 * @var string 11 */ 12 protected $dir = ""; 13 14 /** 15 * 类名与目录名映射数组 16 * 17 * @var array 18 */ 19 protected $map = array(); 20 21 /** 22 * 初始化自动加载类 23 * 24 * @param string $dir 25 * 类文件所在目录 26 * @param array|string $map 27 * 类名称与目录名称映射,字符串方式:如果Zend命名空间映射到Zf2,写法:Zend|Zf2 28 */ 29 public function __construct($dir, $map = []) 30 { 31 if (! $dir) { 32 throw new Exception("类目录不能为空", 2001); 33 } 34 $dirLastChar = substr($dir, - 1, 1); 35 if ($dirLastChar != "/" && $dirLastChar != "\\") { 36 $dir .= DIRECTORY_SEPARATOR; 37 } 38 $this->dir = $dir; 39 40 if (is_string($map)) { 41 $mapTmp = explode(",", $map); 42 $mapList = []; 43 foreach ($mapTmp as $key => $item) { 44 $tmpArr = explode("|", $item); 45 if (count($tmpArr) >= 2) { 46 if ($tmpArr[0] && $tmpArr[1]) { 47 $mapList[$tmpArr[0]] = $tmpArr[1]; 48 } 49 } elseif (count($tmpArr) == 1) { 50 if ($tmpArr[0]) { 51 $mapList[$tmpArr[0]] = $tmpArr[0]; 52 } 53 } 54 } 55 56 $map = $mapList; 57 } 58 59 foreach ($map as $key => $item) { 60 if ($key && $item) { 61 $this->addMap($key, $item); 62 } 63 } 64 } 65 66 function addMap($namespace, $path) 67 { 68 $this->map[$namespace] = $path; 69 } 70 71 /** 72 * 获取类映射数组 73 */ 74 function getMap() 75 { 76 return $this->map(); 77 } 78 79 function clearMap() 80 { 81 $this->map = array(); 82 } 83 84 /** 85 * SPL类自动加载函数 86 * 87 * @param string $className 88 */ 89 public function load($className) 90 { 91 if (! $className) { 92 return false; 93 } 94 $arr = explode("\\", $className); 95 $nameSpace = isset($arr[0]) ? $arr[0] : ""; 96 97 if (! $nameSpace) { 98 return false; 99 } 100 if (! isset($this->map[$nameSpace])) { 101 return false; 102 } 103 unset($arr[0]); 104 105 $fileName = implode(DIRECTORY_SEPARATOR, $arr); 106 $path = $this->dir . $this->map[$nameSpace] . DIRECTORY_SEPARATOR . $fileName . ".php"; 107 require ($path); 108 } 109 }
调用示例
1 require ‘AutoLoad.php‘; 2 $autoload= new AutoLoad("Zend|Zf2"); 3 spl_autoload_register(array($autoload,"load"));
时间: 2024-10-14 01:25:31