php類的自動加載操作實例詳解
本文實例講述了php類的自動加載操作。分享給大家供大家參考,具體如下:
類的自動加載
在外面的頁面中,并不需要去引入類文件,但程序會在需要一個類的時候自動去“動態(tài)加載”該類。
① 創(chuàng)建一個對象的時候new
② 直接使用一個類名(操作靜態(tài)屬性與方法)
使用__autoload魔術(shù)函數(shù)
當出現(xiàn)兩種情況時候,就會調(diào)用該函數(shù),該函數(shù)需要我們預(yù)先定義,在其中寫好加載類文件的通用語句
function __autoload($name){ require './lib/'.$name.'.class.php'; }
使用spl_autoload_register()
用它注冊(聲明)多個可以代替__autoload()作用的函數(shù),自然也得去定義這些函數(shù),并且函數(shù)的作用跟__autoload()作用一樣,不過此時可以應(yīng)對更多的情形
//注冊用于自動加載的函數(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'; } } //如果需要一個類,但當前頁面還沒加載該類 //就會依次調(diào)用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') );
項目場景應(yīng)用
//自動加載 //控制器類 模型類 核心類 //對于所有的類分為可以確定的類以及可以擴展的類 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'; } }
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
相關(guān)文章
php基于PDO實現(xiàn)功能強大的MYSQL封裝類實例
這篇文章主要介紹了php基于PDO實現(xiàn)功能強大的MYSQL封裝類,結(jié)合完整實例形式分析了php基于pdo實現(xiàn)mysql數(shù)據(jù)庫連接、增刪改查、事務(wù)等操作的方法,需要的朋友可以參考下2017-02-02PHP與MongoDB簡介|安全|M+PHP應(yīng)用實例詳解
本篇文章是對PHP中的MongoDB簡介|安全|M+PHP應(yīng)用實例進行了詳細的分析介紹,需要的朋友參考下2013-06-06php從數(shù)據(jù)庫查詢結(jié)果生成樹形列表的方法
這篇文章主要介紹了php從數(shù)據(jù)庫查詢結(jié)果生成樹形列表的方法,涉及php操作html元素生成樹形列表的技巧,非常具有實用價值,需要的朋友可以參考下2015-04-04