spl_autoload_register() && __autoload函数

一、__autoload  

这是一个自动加载函数,在PHP5中,当我们实例化一个未定义的类时,就会触发此函数。

在index.php中,由于没有包含test.class.php,在实例化printit时,自动调用__autoload函数,参数$class的值即为类名printit,此时test.class.php就被包含进来了。  

eg:

test.class.php 
 
<?php 
 
class test { 
 
 function doPrint() {
  echo 'hello world';
 }
}
?> 
 
index.php 
 
<?
function __autoload( $class ) {
 $file = $class . '.class.php';  
 if ( is_file($file) ) {  
  require_once($file);  
 }
} 
 
$obj = new test();
$obj->doPrint();
?>

二、spl_autoload_register()  

spl_autoload_register(),这个函数与__autoload有与曲同工之妙,将__autoload换成自定义函数。但是该自定义函数不会像__autoload自动触发,这时spl_autoload_register()就起作用了,它告诉PHP碰到没有定义的类就执行该自定义函数()。 

<? 
 
class test {
 public static function myAuto( $class ) {
  $file = $class . '.class.php';  
  if (is_file($file)) {  
   require_once($file);  
  } 
 }
} 

class myTest {
  function doPrint() {  
  echo 'hello world';
   }
} 
 

 
spl_autoload_register(  array('test',myAuto)  );

//另一种写法:spl_autoload_register(  "test::myAuto"  ); 
 
$obj = new  myTest ();
$obj->doPrint();
?>
 
原文地址:https://www.cnblogs.com/jamesbd/p/3995343.html