PHP 中的__autoload() 與spl_autoload_register()函數

來源:互聯網
上載者:User

標籤:

__autoload()函數可以實現自動載入所需要的類

用法:

__autoload() 在執行個體化對象時,若沒有引入相關的檔案,就會自動調用這個方法來進行載入。

執行個體:

public function __autoload($className){    $actionPath ="E://project/LiB/Action/".$className.".class.php";    if(!file_exists($actionPath))    {        echo $actionPath."路徑不存在";    }    require_once($actionPath);}

spl_autoload_register()函數

作用:註冊自訂載入函數

比如在檔案中定義一個  loadfile()作為自訂載入函數,但是至少聲明或者定義這個函數後,在執行個體化對象時,程式並不會自動去運行loadfile()這個函數,而會自動運行__autoload()函數。而spl_autoload_register()函數就是讓程式在執行個體化一個對象時組自動調用loadfile()函數。

執行個體:

<?php    class test    {        public function testLoad()        {               echo "這是test類中的testLoad方法";        }    }?><?php    spl_autoload_register(array("AutoLoad", "autoLoadCore"), ‘‘, true); //註冊自動載入方法        //定義自訂載入函數    public static function autoLoadCore($classname)    {        $classPath =  "E://project/LiB/Action/".$className.".class.php";        if(!file_exists($classPath))        {            echo $classPath."路徑不存在";        }        require_once($classPath);    }        $test = new test();    $test->testLoad();?>

結果: 輸出:這是test類中的testLoad方法;

spl_autoload_register()有三個參數

第一個:array($classname,$method),是一個數組,數組有兩個元素,第一個元素表示自動載入方法所在的類,第二個表示自動載入方法的函數名

第二個參數:表示無法成功註冊時是否拋出異常,true/false

第三個參數:true/false,表示是否將函數註冊到自動載入函數隊列之首。

注意:1、spl_autoload_register()實際上建立了 autoload 函數的隊列,按定義時的順序逐個執行(至今我沒有成功實現逐個執行的功能,請各位指點)

2、若使用spl_autoload_register()註冊了新的自動載入函數,那麼原有的__autoload()函數將失效,若需使用__autoload()函數,需要通過spl_autoload_register()再次註冊__autoload()函數,方能在使用此函數

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.