1、打开相应的PHP代码文件。
2、添加“$class = str_replace("\\\\","/",$class);”代码即可。
文件在本地win系统下测试无异常,代码如下:
?
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服务器上异常,报错为 unable to autoload Class xxxxxx
解决方案
根据报错,发现 $class 的值需要形如 stuApp\\dao\\StuInfo 才可行, 文件路径需要将 \\ 转义成 /,因此添加一行代码即可。
?
1
|
$class = str_replace ( "\\\\" , "/" , $class );
|
综上,修改后的自动加载代码如下:
?
1
2
3
4
5
6
7
|
function stu_autoload( $class ){
//路径转义
$class = str_replace ( "\\\\" , "/" , $class ); if ( file_exists ( $class . ".php" )){ require ( $class . ".php" );
} else { die ( "unable to autoload Class $class" );
}
}
spl_autoload_register( "stu_autoload" );
|
知识点扩充:
在外面的页面中,并不需要去引入类文件,但程序会在需要一个类的时候自动去“动态加载”该类。
① 创建一个对象的时候new
② 直接使用一个类名(操作静态属性与方法)
使用spl_autoload_register()
用它注册(声明)多个可以代替__autoload()作用的函数,自然也得去定义这些函数,并且函数的作用跟__autoload()作用一样,不过此时可以应对更多的情形
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//注册用于自动加载的函数
spl_autoload_register( "model" );
spl_autoload_register( "controll" );
//分别定义两个函数
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' ;
}
}
|
?
1
2
3
4
5
6
7
|
//若注册的是方法而不是函数,则需要使用数组
spl_autoload_register(
//非静态方法
array ( $this , 'model' ),
//静态方法
array ( __CLASS__ , 'controller' )
);
|
项目场景应用
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//自动加载
//控制器类 模型类 核心类
//对于所有的类分为可以确定的类以及可以扩展的类
spl_autoload_register( 'autoLoad' );
//先处理确定的框架核心类
function autoLoad( $name ){
//类名与类文件映射数组
$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类自动加载失败的处理方案及实例代码的文章就介绍到这了,更多相关php类自动加载失败的解决办法内容请搜索快网idc以前的文章或继续浏览下面的相关文章希望大家以后多多支持快网idc!
原文链接:https://www.py.cn/php/jiaocheng/33918.html
相关文章
猜你喜欢
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
- 64M VPS建站:怎样选择合适的域名和SSL证书? 2025-06-10
- 64M VPS建站:怎样优化以提高网站加载速度? 2025-06-10
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-06-04 49
-
2025-05-29 46
-
2025-05-29 17
-
2025-05-29 49
-
2025-05-27 27
热门评论