php自动加载的两个函数__autoload和__sql_autoload_register

一、__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();
?>
上一篇:常用js,css文件统一加载方法,并在加载之后调用回调函数


下一篇:C++语言笔记系列之十六——赋值兼容规则&多继承的二义性