php spl_autoload_register與__autoload方法詳解

來源:互聯網
上載者:User

php教程 spl_autoload_register與__autoload方法詳解

在談到架構自動載入類的方面,我大概翻了一下,現在主流的架構系統都使用spl_autoload_register函數,而非__autoload函數。

function my_own_loader($classname)
{
    $class_file = strtolower($classname).".php";
    if (file_exists($class_file)){
        require_once($class_file);
    }
}

spl_autoload_register("my_own_loader");

$a = new A();
__autoload 方法在 spl_autoload_register 後會失效,因為 autoload_func 函數指標已指向 spl_autoload 方法
* 可以通過下面的方法來把 _autoload 方法加入 autoload_functions list

spl_autoload_register( '__autoload' );

此外我們還可以使用我們自訂的載入方法:

第一種函數式:

function my_own_loader($classname)
{
    $class_file = strtolower($classname).".php";
    if (file_exists($class_file)){
        require_once($class_file);
    }
}

spl_autoload_register("my_own_loader");

$a = new A();

第二種類式:class Loader
{
    public static function my_own_loader($classname)
    {
        $class_file = strtolower($classname).".php";
        if (file_exists($class_file)){
            require_once($class_file);
        }
    }
}

// 通過數組的形式傳遞類和方法的名稱
spl_autoload_register(array("my_own_loader","Loader"));

$a = new A();
spl_autoload_register()函數應該是主流架構使用最多的也是非常核心的函數之一,可實現自動註冊函數和類,實作類別似__autoload() 函數功能,簡化了類的調用與載入,提高了工作的效率。

支援版本:PHP 5 >= 5.1.2

至於效率問題。php手冊上有如此之話:

bool spl_autoload_register ([ callback $autoload_function ] )

將函數註冊到SPL __autoload函數棧中。如果該棧中的函數尚未啟用,則啟用它們。貌似他麼指向同一個堆棧,效率上都是大哥二哥的問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.