本文實例講述了php類的自動加載操作。分享給大家供大家參考,具體如下:
類的自動加載
在外面的頁面中,并不需要去引入類文件,但程序會在需要一個類的時候自動去“動態(tài)加載”該類。
① 創(chuàng)建一個對象的時候new
② 直接使用一個類名(操作靜態(tài)屬性與方法)
使用__autoload魔術函數(shù)
當出現(xiàn)兩種情況時候,就會調用該函數(shù),該函數(shù)需要我們預先定義,在其中寫好加載類文件的通用語句
function __autoload($name){ require './lib/'.$name.'.class.php';}使用spl_autoload_register()
用它注冊(聲明)多個可以代替__autoload()作用的函數(shù),自然也得去定義這些函數(shù),并且函數(shù)的作用跟__autoload()作用一樣,不過此時可以應對更多的情形
//注冊用于自動加載的函數(shù)spl_autoload_register("model");spl_autoload_register("controll");//分別定義兩個函數(shù)function model($name){ $file = './model/'.$name.'.class.php'; if(file_exists($file)){ require './model/'.$name.'.class.php'; }}//如果需要一個類,但當前頁面還沒加載該類//就會依次調用model()和controll(),直到找到該類文件加載,否則就報錯function controll($name){ $file = './controll/'.$name.'.class.php'; if(file_exists($file)){ require './controll/'.$name.'.class.php'; }}//若注冊的是方法而不是函數(shù),則需要使用數(shù)組spl_autoload_register( //非靜態(tài)方法 array($this,'model'), //靜態(tài)方法 array(__CLASS__,'controller'));
項目場景應用
//自動加載//控制器類 模型類 核心類//對于所有的類分為可以確定的類以及可以擴展的類spl_autoload_register('autoLoad');//先處理確定的框架核心類function autoLoad($name){ //類名與類文件映射數(shù)組 $framework_class_list = array( 'mySqldb' => './framework/mySqldb.class.php' ); if(isset($framework_class_list[$name])){ require $framework_class_list[$name]; }elseif(substr($name,-10)=='Controller'){ require './application/'.PLATFORM.'/controller/'.$name.'.class.php'; }elseif(substr($name,-6)=='Modele'){ require './application/'.PLATFORM.'/modele/'.$name.'.class.php'; }}希望本文所述對大家PHP程序設計有所幫助。
新聞熱點
疑難解答
圖片精選