1、打開(kāi)相應(yīng)的PHP代碼文件。
2、添加“$class = str_replace("\\","/",$class);”代碼即可。
文件在本地win系統(tǒng)下測(cè)試無(wú)異常,代碼如下:
1
2
3
4
5
6
|
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ù)器上異常,報(bào)錯(cuò)為 unable to autoload Class xxxxxx
解決方案
根據(jù)報(bào)錯(cuò),發(fā)現(xiàn) $class 的值需要形如 stuApp\dao\StuInfo 才可行, 文件路徑需要將 \ 轉(zhuǎn)義成 /,因此添加一行代碼即可。
1
|
$class = str_replace ( "\\" , "/" , $class ); |
綜上,修改后的自動(dòng)加載代碼如下:
1
2
3
4
5
6
7
|
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" ); |
知識(shí)點(diǎn)擴(kuò)充:
類(lèi)的自動(dòng)加載
在外面的頁(yè)面中,并不需要去引入類(lèi)文件,但程序會(huì)在需要一個(gè)類(lèi)的時(shí)候自動(dòng)去“動(dòng)態(tài)加載”該類(lèi)。
① 創(chuàng)建一個(gè)對(duì)象的時(shí)候new
② 直接使用一個(gè)類(lèi)名(操作靜態(tài)屬性與方法)
使用spl_autoload_register()
用它注冊(cè)(聲明)多個(gè)可以代替__autoload()作用的函數(shù),自然也得去定義這些函數(shù),并且函數(shù)的作用跟__autoload()作用一樣,不過(guò)此時(shí)可以應(yīng)對(duì)更多的情形
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//注冊(cè)用于自動(dòng)加載的函數(shù) spl_autoload_register( "model" ); spl_autoload_register( "controll" ); //分別定義兩個(gè)函數(shù) function model( $name ){ $file = './model/' . $name . '.class.php' ; if ( file_exists ( $file )){ require './model/' . $name . '.class.php' ; } } //如果需要一個(gè)類(lèi),但當(dāng)前頁(yè)面還沒(méi)加載該類(lèi) //就會(huì)依次調(diào)用model()和controll(),直到找到該類(lèi)文件加載,否則就報(bào)錯(cuò) function controll( $name ){ $file = './controll/' . $name . '.class.php' ; if ( file_exists ( $file )){ require './controll/' . $name . '.class.php' ; } } |
1
2
3
4
5
6
7
|
//若注冊(cè)的是方法而不是函數(shù),則需要使用數(shù)組 spl_autoload_register( //非靜態(tài)方法 array ( $this , 'model' ), //靜態(tài)方法 array ( __CLASS__ , 'controller' ) ); |
項(xiàng)目場(chǎng)景應(yīng)用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//自動(dòng)加載 //控制器類(lèi) 模型類(lèi) 核心類(lèi) //對(duì)于所有的類(lèi)分為可以確定的類(lèi)以及可以擴(kuò)展的類(lèi) spl_autoload_register( 'autoLoad' ); //先處理確定的框架核心類(lèi) function autoLoad( $name ){ //類(lèi)名與類(lèi)文件映射數(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類(lèi)自動(dòng)加載失敗的處理方案及實(shí)例代碼的文章就介紹到這了,更多相關(guān)php類(lèi)自動(dòng)加載失敗的解決辦法內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://www.py.cn/php/jiaocheng/33918.html