1. 程式人生 > >php中自動加載類_autoload()和spl_autoload_register()實例詳解

php中自動加載類_autoload()和spl_autoload_register()實例詳解

http obj 自動加載 完整 echo register auto 文件名 代碼

一、_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();

上面完整代碼下載地址:http://pan.baidu.com/s/1i5DZSmp

密碼:eexc

php中自動加載類_autoload()和spl_autoload_register()實例詳解