spl_autoload_register()和__autoload()区别

这是一个自动加载函数,在PHP5中,当我们实例化一个未定义的类时,就会触发此函数。看下面例子:

1
2
3
4
5
6
7
<?php
class PRINTIT {
 function doPrint() {
 echo 'hello world';
 }
}
?>

  

1
2
3
4
5
6
7
8
<?<br>function __autoload( $class ) {
 $file = $class . '.class.php';
 if ( is_file($file) ) {
 require_once($file);
 }
}
$obj = new PRINTIT();
$obj->doPrint();?>

运行index.php后正常输出hello world

二、spl_autoload_register()

再看spl_autoload_register(),这个函数与__autoload有与曲同工之妙,看个简单的例子:

1
2
3
4
5
6
7
8
9
10
<?
function loadprint( $class ) {
 $file = $class . '.class.php';
 if (is_file($file)) {
 require_once($file);
 }
}
spl_autoload_register( 'loadprint' );
$obj = new PRINTIT();
$obj->doPrint();?>

将__autoload换成loadprint函数。但是loadprint不会像__autoload自动触发,这时spl_autoload_register()就起作用了,它告诉PHP碰到没有定义的类就执行loadprint()。

spl_autoload_register() 调用静态方法

1
2
3
4
5
6
7
8
9
10
11
12
13
<?
class test {
 public static function loadprint( $class ) {
 $file = $class . '.class.php';
 if (is_file($file)) {
  require_once($file);
 }
 }
}
spl_autoload_register( array('test','loadprint') );
//另一种写法:spl_autoload_register( "test::loadprint" );
$obj = new PRINTIT();
$obj->doPrint();?>

 

使用spl_autoload_register()的好处是不可言喻的:
(1)自动加载对象更加方便,很多框架都是这样做的

(2)你要知道__autoload()函数只能存在一次啊,spl_autoload_register()当然能注册多个函数

(3)SPL函数很丰富,提供了更多功能,如spl_autoload_unregister()注销已经注册的函数、spl_autoload_functions()返回所有已经注册的函数等。

 

 

 

 

 

 

 

  

 

 

  

 

posted @   飞龙在生  阅读(151)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示