類的自動加載是指,在外面的頁面中,并不需要去“引入”類文件,但是程序會在需要的時候動態(tài)加載需要的類文件。
方法1:使用__autoload魔術(shù)函數(shù)
當(dāng)程序需要某個類時,就會去調(diào)用該函數(shù),該函數(shù)我們需要自己去定義并在其中寫好加載類文件的通用語句。
<?php    //需要類是自動調(diào)用,而且會傳進(jìn)來一個類名,這個案例的文件名為21A.class.php,類名為A     function __autoload($className){      require "./21".$className.".class.php";    }    $o1 = new A();    $o1->v1 = 10;    echo "<br/>v1:".$o1->v1;  ?>方法2:使用spl_autoload_register函數(shù)
該函數(shù)的作用是生命多個可以用來代替autoload函數(shù)作用的函數(shù),語法如下:spl_autoload_regist("函數(shù)名1");如果用spl_autoload_register,autoload就失效了。
<?php    //注冊兩個用于自動加載的函數(shù)名    spl_autoload_register('auto1');    spl_autoload_register('auto2');    function auto1($className){      $file = "./21".$className.".class.php";      if(file_exists($file)){        require "./21".$className.".class.php";      }    }    function auto1($className){      $file = "./22".$className.".class.php";      if(file_exists($file)){        require "./22".$className.".class.php";      }    }    //如果需要一個雷,但這個頁面還沒有記載,就會依次調(diào)用auto1和auto2,知道找到該類文件并加載  ?>以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點
疑難解答
圖片精選