您的位置:首页 > 编程语言 > PHP开发

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

2016-07-11 18:04 746 查看
一、__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();
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: