構建自己的PHP框架之自動加載類中詳解spl_autoload_register()函數


在了解這個函數之前先來看另一個函數:__autoload。  

一、__autoload  

這是一個自動加載函數,在PHP5中,當我們實例化一個未定義的類時,就會觸發此函數。看下面例子:  

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

運行index.PHP后正常輸出hello world。在index.php中,由於沒有包含printit.class.php,在實例化printit時,自動調用__autoload函數,參數$class的值即為類名printit,此時printit.class.php就被引進來了。  

在面向對象中這種方法經常使用,可以避免書寫過多的引用文件,同時也使整個系統更加靈活。  

二、spl_autoload_register()  

再看spl_autoload_register(),這個函數與__autoload有與曲同工之妙,看個簡單的例子:  

<?
function loadprint( $class ) {
 $file = $class . '.class.php';  
 if (is_file($file)) {  
  require_once($file);  
 } 
} 
 
spl_autoload_register( 'loadprint' ); 
 
$obj = new PRINTIT();
$obj->doPrint();
?>

將__autoload換成loadprint函數。但是loadprint不會像__autoload自動觸發,這時spl_autoload_register()就起作用了,它告訴PHP碰到沒有定義的類就執行loadprint()。 

spl_autoload_register() 調用靜態方法 

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM