PHP之自動加載類

咱們說說php的自動加載類,這對於搞開發的兄弟比較重要。
當項目規模比較小的時候,咱們能夠手動包含進來類定義文件或者直接定義而不包含。但是,若是咱們的項目比較大的時候, 就不得不一個一個的將大量類定義文件包含進來,不但麻煩,並且不美觀,讓人眼暈。這時咱們就能夠用php的自動包含類定義文件的方法了。

先定義一個用於引用的類:
<?php
// test.class.php
class test {

  public function __construct(){
    print 'test class initialized!';
  }
}

一、方法一:手動包含類

<?php
// index.php
define('ROOT',dirname(__FILE__));
require_once ROOT.'/test.class.php';
$t = new test();

二、方法二:使用函數__autoload實現自動加載類

在 PHP 5 中,再也不須要這樣了。能夠定義一個 __autoload 函數,它會在試圖使用還沒有被定義的類時自動調用。經過調用此函數,腳本引擎在 PHP 出錯失敗前有了最後一個機會加載所需的類。

<?php
// index.php
define('ROOT',dirname(__FILE__));

function __autoload($class_name){
                $class_file = ROOT.'/'.$class_name.'.class.php';
                if(file_exists($class_file)){
                                require_once $class_file;
                }else{
                                print 'class: '.$class_file.' not found!';
                }
}
$t = new test();


三、方法三:使用SPL函數spl_autoload_register
此函數在php版本>=5.1.0時可用
使用這個函數更方便,由於咱們能夠自定義一個或多個自動加載類函數,而後使用spl_autoload_register函數註冊咱們定義的函數了,以下:
<?php
// index.php
define('ROOT',dirname(__FILE__));

function my_autoload($class_name){
  print 'my_autoload';
  $class_file = ROOT.'/'.$class_name.'.class.php';
  if(file_exists($class_file)){
      require_once $class_file;
  }else{
      print 'class: '.$class_file.' not found!';
  }
}
spl_autoload_register('my_autoload');
$t = new test();

注意:當咱們用函數spl_autoload_register註冊咱們自定義的自動加載類函數後,原來的自動加載類函數
__autoload函數就無效了,除非也將其註冊進來。

最後咱們說說set_include_path
咱們能夠設置文件的默認包含路徑,就不用在包含文件時加前面的目錄了, 好比咱們設置 set_include_path(get_include_path().PATH_SEPARATOR.ROOT.'/database'), 這樣咱們在包含文件時就寫:include mysql.class.php就能夠了,不用再寫成這樣了: include ROOT.'/database/mysql.class.php'
相關文章
相關標籤/搜索