您的位置:首页 > 其它

spl_autoload_register和__autoload

2015-10-09 11:12 190 查看
1.实例化一个[b]未定义的类时会触发[/b]

2.类存在继承关系时,被继承的类没有引入的情况下,会触发 (继承关系的两个类必须在同一个目录下)

__autoload

  实例化PRINTIT类,'PRINTIT'作为参数,传递到__autoload()中,并作为文件名称加载

function __autoload( $class ) {
$file = $class . '.class.php';
if ( is_file($file) ) {
require_once('INCPATH'.$file);
}
}

$obj = new PRINTIT();
$obj->doPrint();


  

spl_autoload_register

  spl_autoload_register 这种方法提供了更灵活的方式去注册加载器。根据场景的不同,定义不同的加载函数,再依据条件分别注册成加载器。

加载器为函数

function loadprint( $class ) {
$file = $class . '.class.php';
if (is_file($file)) {
require_once($file);
}
}

spl_autoload_register( 'loadprint' );

$obj = new PRINTIT();
$obj->doPrint();


加载器为对象方法

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();


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: