php自動(dòng)加載
php自動(dòng)載方法有兩種.
第一種方案用__autoload,這個(gè)函數(shù)較簡(jiǎn)單,也較弱.
但有一問(wèn)題沒(méi)有解決, 就是在include前判斷文件是否存在的問(wèn)題.
1
2
3
4
5
6
7
8
9
10
11
12
|
set_include_path( 'aa' . PATH_SEPARATOR . get_include_path()); function __autoload( $className ) { //如果加這個(gè)檢測(cè), 因?yàn)榇宋募辉诋?dāng)前目錄下,它就會(huì)檢測(cè)不到文件存在, //但include是能成功的 if ( file_exists ( $className . '.php' )) { include_once ( $className . '.php' ); } else { exit ( 'no file' ); } } $a = new Acls(); |
第二種方案用spl自動(dòng)加載,這里具體說(shuō)一下這個(gè).
spl_autoload_register()
一個(gè)簡(jiǎn)單的例子
1
2
3
4
5
6
7
8
9
10
11
|
set_include_path( 'aa' . PATH_SEPARATOR . get_include_path()); //function __autoload($className) //{ // if (file_exists($className . '.php')) { // include_once($className . '.php'); // } else { // exit('no file'); // } //} spl_autoload_register(); $a = new Acls(); |
spl_autoload_register()會(huì)自動(dòng)先調(diào)用spl_autoload()在路徑中查找具有小寫(xiě)文件名的".php"程序.默認(rèn)查找的擴(kuò)展名還有".ini",還可以用spl_autoload_extenstions()注冊(cè)擴(kuò)展名.
在找不到的清況下,還可以通過(guò)自己定義函數(shù)查找
如
1
2
3
4
5
6
7
8
9
10
11
12
|
function loader1( $class ) { //自己寫(xiě)一些加載的代碼 } function loader2( $class ) { //當(dāng)loader1()找不到時(shí),我來(lái)找 } spl_autoload_register( 'loader1' ); spl_autoload_register( 'loader2' ); |
還可以更多........
MVC框架是如何實(shí)現(xiàn)自動(dòng)加載的
首先設(shè)置路徑
$include = array('application/controllers', 'application/models', 'application/library');
set_include_path(get_include_path() . PATH_SEPARATOR .implode(PATH_SEPARATOR, $config['include']));
在獲取URL,解析出控制器與方法.
然后設(shè)置自動(dòng)加載
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class Loader { /** * 自動(dòng)加載類 * @param $class 類名 */ public static function autoload( $class ) { $path = '' ; $path = str_replace ( '_' , '/' , $class ) . '.php' ; include_once ( $path ); } } /** * sql自動(dòng)加載 */ spl_autoload_register( array ( 'Loader' , 'autoload' )); |
路由,實(shí)例化控制器,調(diào)用方法,你寫(xiě)的東西就開(kāi)始執(zhí)行了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
/** * 路由 */ public function route() { if ( class_exists ( $this ->getController())) { $rc = new ReflectionClass( $this ->getController()); if ( $rc ->hasMethod( $this ->getAction())) { $controller = $rc ->newInstance(); $method = $rc ->getMethod( $this ->getAction()); $method ->invoke( $controller ); } else throw new Exception( 'no action' ); } else throw new Exception( 'no controller' ); } |
初步的自動(dòng)加載就完成了
到此這篇關(guān)于PHP實(shí)現(xiàn)自動(dòng)加載機(jī)制的文章就介紹到這了,更多相關(guān)PHP自動(dòng)加載內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://www.cnblogs.com/yuxing/archive/2010/06/19/1760742.html