php類自動加載失敗的處理方案及實例代碼
1、打開相應(yīng)的PHP代碼文件。
2、添加“$class = str_replace("\\","/",$class);”代碼即可。
文件在本地win系統(tǒng)下測試無異常,代碼如下:
function stu_autoload($class){
if(file_exists($class.".php")){ require ( $class.".php");
}else{ die("unable to autoload Class $class");
}
}
spl_autoload_register("stu_autoload");
部署到Ubuntu服務(wù)器上異常,報錯為 unable to autoload Class xxxxxx
解決方案
根據(jù)報錯,發(fā)現(xiàn) $class 的值需要形如 stuApp\dao\StuInfo 才可行, 文件路徑需要將 \ 轉(zhuǎn)義成 /,因此添加一行代碼即可。
$class = str_replace("\\","/",$class);
綜上,修改后的自動加載代碼如下:
function stu_autoload($class){
//路徑轉(zhuǎn)義
$class = str_replace("\\","/",$class); if(file_exists($class.".php")){ require ( $class.".php");
}else{ die("unable to autoload Class $class");
}
}
spl_autoload_register("stu_autoload");
知識點擴充:
類的自動加載
在外面的頁面中,并不需要去引入類文件,但程序會在需要一個類的時候自動去“動態(tài)加載”該類。
① 創(chuàng)建一個對象的時候new
② 直接使用一個類名(操作靜態(tài)屬性與方法)
使用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';
}
}
//如果需要一個類,但當(dāng)前頁面還沒加載該類
//就會依次調(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)php類自動加載失敗的解決辦法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
PHP實現(xiàn)創(chuàng)建以太坊錢包轉(zhuǎn)賬等功能
這篇文章主要介紹了PHP實現(xiàn)創(chuàng)建以太坊錢包轉(zhuǎn)賬等功能,對以太坊感興趣的同學(xué),可以參考下2021-04-04
php自定義函數(shù)實現(xiàn)二維數(shù)組排序功能
這篇文章主要介紹了php自定義函數(shù)實現(xiàn)二維數(shù)組排序功能,涉及php針對數(shù)組的判斷、遍歷、轉(zhuǎn)換、排序等相關(guān)操作技巧,需要的朋友可以參考下2016-07-07

