Jamers Posted September 7, 2017 Report Share Posted September 7, 2017 日常开发中经常需要按照一定的规则将类文件放在指定目录,正常情况下需要include或require一堆文件,非常的不方便,一般来说可以使用spl_autoload_register进行自动加载,大型项目开发时还会用到namespace,特意整理了一份支持几种方式的自动调用。 /** * 根命名空间自动加载类 * 支持命名空间及正常方式加载类 * @since 2017-09-07 * @author Jamers */ namespace { @session_start(); if (!defined("ROOT")) { define("ROOT",dirname(__FILE__).DIRECTORY_SEPARATOR); } if (defined('STDIN')) chdir(dirname(__FILE__)); function autoload($cls) { $base = 'class'.DIRECTORY_SEPARATOR; if (strtolower($cls)=='smarty') { $file = ROOT.'libs/Smarty-3.1.30/Smarty.class.php'; }else{ $a = explode('\\',$cls); $a[count($a)-1] = 'Cls_'.ucfirst($a[count($a)-1]); $file = ROOT.$base.implode(DIRECTORY_SEPARATOR,$a).'.php'; } if (file_exists($file)) { include_once($file); }else{ try { $err = 'Can\'t found '.$file; throw new Exception($err); }catch(Exception $e){ exit($e->getFile().':'.$e->getLine().'<br><br> "'.$e->getMessage().'"<br><br><b>Track:</b><br>'.$e->getTraceAsString()); } } return true; } spl_autoload_register('autoload'); } Link to comment Share on other sites More sharing options...
Recommended Posts
Please sign in to comment
You will be able to leave a comment after signing in
Sign In Now