php spl_autoload_register與__autoload方法詳解
在談到框架自動(dòng)加載類(lèi)的方面,我大概翻了一下,現(xiàn)在主流的框架系統(tǒng)都使用spl_autoload_register函數(shù),而非__autoload函數(shù).
- 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 后會(huì)失效,因?yàn)?autoload_func 函數(shù)指針已指向 spl_autoload 方法
* 可以通過(guò)下面的方法來(lái)把 _autoload 方法加入 autoload_functions list
spl_autoload_register( '__autoload' );
此外我們還可以使用我們自定義的加載方法:
第一種函數(shù)式:
- 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();
第二種類(lèi)式:class Loader
- {
- public static function my_own_loader($classname)
- {
- $class_file = strtolower($classname).".php";
- if (file_exists($class_file)){
- require_once($class_file);
- }
- }
- }
- // 通過(guò)數(shù)組的形式傳遞類(lèi)和方法的名稱(chēng)
- spl_autoload_register(array("my_own_loader","Loader"));
- $a = new A();
spl_autoload_register()函數(shù)應(yīng)該是主流框架使用最多的也是非常核心的函數(shù)之一,可實(shí)現(xiàn)自動(dòng)注冊(cè)函數(shù)和類(lèi),實(shí)現(xiàn)類(lèi)似__autoload() 函數(shù)功能,簡(jiǎn)化了類(lèi)的調(diào)用與加載,提高了工作的效率.
支持版本:PHP 5 >= 5.1.2
至于效率問(wèn)題,php手冊(cè)上有如此之話:
bool spl_autoload_register ([ callback $autoload_function ] )
將函數(shù)注冊(cè)到SPL __autoload函數(shù)棧中,如果該棧中的函數(shù)尚未激活,則激活它們,貌似他么指向同一個(gè)堆棧,效率上都是大哥二哥的問(wèn)題.
新聞熱點(diǎn)
疑難解答