PHP spl_autoload_register()函數使用

和 spl_autoload_register函數相關的另一個函數是__autoload();
__autoload()是一個自動加載函數,在PHP5中,當我們實例化一個未定義的類時,就會觸發此函數。

看下面例子: 
新建文件Printer.class.php
<?php
class Printer {
  function doPrint() {
    echo 'hello world';
  }
}
?>

再建文件 index.php
<?php
function __autoload( $class ) {
$file = $class . '.class.php';
if ( is_file($file) ) {
return require_once($file);
}
}
$obj = new Printer();
$obj->doPrint();
?>

運行index.php後正常輸出hello world。在index.php中,由於沒有包含Printer.class.php,在實例化Printer時,自動調用__autoload函數,參數$class的值即爲類名Printer,此時Printer.class.php就被引進來了。 
在面向對象中這種方法經常使用,可以避免書寫過多的引用文件,同時也使整個系統更加靈活。 

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

    public static function loader($class){
        $file = $class . '.class.php';
        if(is_file($file)){
            echo 'VLoader::loader<br />';
            return require_once($file);
        }
    }
}

//spl_autoload_register(array('VLoader','loader')); //第一種調用方法,數組調用方法
spl_autoload_register('VLoader::loader');  //第二種調用方法,靜態調用方法

$p = new Printer();
$p->doPrint();

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章