PHP函數之spl_autoload_register和spl_autoload_unregister

spl_autoload_register
首先:理解__autoload()函數
當同一個文件中,實例化一個不存在的類,會自動調用__autoload()函數
用法:將類名傳入,找到__autoload($class);中的路徑,包含路徑中的類文件

<?php   
function __autoload($class)   
{   
$file = $class . '.php';   
if (is_file($file)) {   
require_once($file);   
}   
}   

$a = new A();
理解spl_autoload_register(array(className,funcName)),就是註冊一個自己的自動加載函數
參數:定義類名,方法名,當實例化一個不存在的類時,調用className類下的funcName方法
好處:可以多次註冊不同的函數。

用法:

<?php   
function loader($class)   
{   
    $file = $class . '.php';   
    if (is_file($file)) {   
        require_once($file);   
    }   
}   

spl_autoload_register('loader');   

$a = new A();

spl_autoload_unregister(funcName)
    看名字就清楚,這個函數的作用跟spl_autoload_register剛好相反,它是註銷註冊了的自動加載函數用的
    如:spl_autoload_unregister(’loader‘),則在之後的操作中,實例化一個當前頁面不存在的類,不會調用loader函數。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章