php中自動載入類_autoload()和spl_autoload_register()執行個體詳解

來源:互聯網
上載者:User

標籤:代碼下載   定義   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()執行個體詳解

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.