spl_autoload_register()和__autoload()区别
这是一个自动加载函数,在PHP5中,当我们实例化一个未定义的类时,就会触发此函数。看下面例子:
<?php
class PRINTIT {
function doPrint() {
echo 'hello world';
}
}
?>
<?
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有与曲同工之妙,看个简单的例子:
<?
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() 调用静态方法
<?
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()返回所有已经注册的函数等。
本文来自博客园,作者:飞龙在生,转载请注明原文链接:https://www.cnblogs.com/flzs/p/14273351.html
浙公网安备 33010602011771号