spl_autoload_register和__autoload

1.实例化一个未定义的类时会触发

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

 

原文地址:https://www.cnblogs.com/mysic/p/4863391.html