《PHP實(shí)戰(zhàn):php類的自動加載操作實(shí)例詳解》要點(diǎn):
本文介紹了PHP實(shí)戰(zhàn):php類的自動加載操作實(shí)例詳解,希望對您有用。如果有疑問,可以聯(lián)系我們。
PHP實(shí)戰(zhàn)本文實(shí)例講述了php類的自動加載操作.分享給大家供大家參考,具體如下:
PHP實(shí)戰(zhàn)類的自動加載
PHP實(shí)戰(zhàn)在外面的頁面中,并不需要去引入類文件,但程序會在需要一個類的時候自動去“動態(tài)加載”該類.
PHP實(shí)戰(zhàn)① 創(chuàng)建一個對象的時候new
PHP實(shí)戰(zhàn)② 直接使用一個類名(操作靜態(tài)屬性與方法)
PHP實(shí)戰(zhàn)使用__autoload魔術(shù)函數(shù)
PHP實(shí)戰(zhàn)當(dāng)出現(xiàn)兩種情況時候,就會調(diào)用該函數(shù),該函數(shù)需要我們預(yù)先定義,在其中寫好加載類文件的通用語句
PHP實(shí)戰(zhàn)
function __autoload($name){
require './lib/'.$name.'.class.php';
}
PHP實(shí)戰(zhàn)使用spl_autoload_register()
PHP實(shí)戰(zhàn)用它注冊(聲明)多個可以代替__autoload()作用的函數(shù),自然也得去定義這些函數(shù),并且函數(shù)的作用跟__autoload()作用一樣,不過此時可以應(yīng)對更多的情形
PHP實(shí)戰(zhàn)
//注冊用于自動加載的函數(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';
}
}
//如果需要一個類,但當(dāng)前頁面還沒加載該類
//就會依次調(diào)用model()和controll(),直到找到該類文件加載,否則就報錯
function controll($name){
$file = './controll/'.$name.'.class.php';
if(file_exists($file)){
require './controll/'.$name.'.class.php';
}
}
PHP實(shí)戰(zhàn)
//若注冊的是方法而不是函數(shù),則需要使用數(shù)組
spl_autoload_register(
//非靜態(tài)方法
array($this,'model'),
//靜態(tài)方法
array(__CLASS__,'controller')
);
PHP實(shí)戰(zhàn)項(xiàng)目場景應(yīng)用
PHP實(shí)戰(zhàn) //自動加載 //控制器類 模型類 核心類 //對于所有的類分為可以確定的類以及可以擴(kuò)展的類 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實(shí)戰(zhàn)更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《PHP基本語法入門教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
PHP實(shí)戰(zhàn)希望本文所述對大家PHP程序設(shè)計有所幫助.
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/3182.html