標籤:代碼下載 定義 cti 通過 smp 寫法 style array register
一、_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()執行個體詳解