一、__autoload
这是一个自动加载函数,在PHP5中,当我们实例化一个未定义的类时,就会触发此函数。看下面例子:
printit.class.php //文件 <?php class PRINTIT { function doPrint() {
echo 'hello world';
}
}
?> index.php //文件 <?php
function __autoload( $class ) {
$file = $class . '.class.php';
if ( is_file($file) ) {
require_once($file);
}
} $obj = new PRINTIT();
$obj->doPrint();
?>
二、spl_autoload_register()
1、它告诉PHP碰到没有定义的类就执行指定的类;
<?php
function loadprint( $class ) {
$file = $class . '.class.php';
if (is_file($file)) {
require_once($file);
}
} spl_autoload_register( 'loadprint' ); $obj = new PRINTIT();
$obj->doPrint();
?>
2、spl_autoload_register() 调用静态方法
<?php
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();
?>