1. 程式人生 > >_autoload 自動加載類和spl_autoload_register()函數

_autoload 自動加載類和spl_autoload_register()函數

obj title 技術分享 .class auto 自己 req tool ()

一、_autoload 自動加載類:當我們實例化一個未定義的類時,就會觸此函數。到了php7.1以後版本不支持此函數好像拋棄了

  新建一個類文件名字自己隨便去:news類在auto.php文件裏面去實例news類而沒有引入該類,可以用_autoload自動加載方法類去處理.

  news.class.php文件

class news{ 
    function do_new() {
        echo ‘aaa‘;
    }
}

  auto.php文件使用_autoload函數要定義函數體自己去定義

技術分享
function __autoload( $class ) {
    $file = $class . ‘.class.php‘;
    if ( is_file($file) ) {
        require_once($file);
    }
} 
$obj = new news();
$obj->do_new();
技術分享

二、spl_autoload_register()這個函數(PHP 5 >= 5.1.2)與__autoload有與曲同工之妙,通過加載自己建的函數裏面處理加載文件,但是文件變量可以自動加入參數

  動態:實例調用的文件還是news.class.php實例化,spl_autoload文件如下:

技術分享
function load($class){ //定義引用文件的函數
    $file = $class . ‘.class.php‘;  
    if (is_file($file)) {  
        require_once($file);  
    }
}
spl_autoload_register( ‘load‘ ); //調用自己定義的load函數
$obj = new news();
$obj->do_new();
技術分享

  靜態:spl_autoload_register() 調用靜態方法

技術分享
class n_static {
    public static function load( $class ) {
        $file = $class . ‘.class.php‘;  
        if(is_file($file)) {  
            require_once($file);  
        } 
    }
} 
spl_autoload_register(  array(‘n_static‘,‘load‘)  );
//另一種寫法:spl_autoload_register(  "n_static::load"  ); 
$obj = new news();
$obj->do_new();

_autoload 自動加載類和spl_autoload_register()函數