首页 > 语言 > PHP > 正文

php spl_autoload_register与__autoload方法详解

2024-09-04 11:43:39
字体:大 中 小
来源:转载
供稿:网友

php spl_autoload_register与__autoload方法详解

在谈到框架自动加载类的方面,我大概翻了一下,现在主流的框架系统都使用spl_autoload_register函数,而非__autoload函数.

  1. function my_own_loader($classname) 
  2. { 
  3.     $class_file = strtolower($classname).".php"; 
  4.     if (file_exists($class_file)){ 
  5.         require_once($class_file); 
  6.     } 
  7. } 
  8.  
  9. spl_autoload_register("my_own_loader"); 
  10.  
  11. $a = new A(); 

__autoload 方法在 spl_autoload_register 后会失效,因为 autoload_func 函数指针已指向 spl_autoload 方法

* 可以通过下面的方法来把 _autoload 方法加入 autoload_functions list

spl_autoload_register( '__autoload' );

此外我们还可以使用我们自定义的加载方法:

第一种函数式:

  1. function my_own_loader($classname) 
  2. { 
  3.     $class_file = strtolower($classname).".php"; 
  4.     if (file_exists($class_file)){ 
  5.         require_once($class_file); 
  6.     } 
  7. } 
  8.  
  9. spl_autoload_register("my_own_loader"); 
  10.  
  11. $a = new A(); 

第二种类式:class Loader

  1. { 
  2.     public static function my_own_loader($classname) 
  3.     { 
  4.         $class_file = strtolower($classname).".php"; 
  5.         if (file_exists($class_file)){ 
  6.             require_once($class_file); 
  7.         } 
  8.     } 
  9. } 
  10.  
  11. // 通过数组的形式传递类和方法的名称 
  12. spl_autoload_register(array("my_own_loader","Loader")); 
  13.  
  14. $a = new A(); 

spl_autoload_register()函数应该是主流框架使用最多的也是非常核心的函数之一,可实现自动注册函数和类,实现类似__autoload() 函数功能,简化了类的调用与加载,提高了工作的效率.

支持版本:PHP 5 >= 5.1.2

至于效率问题,php手册上有如此之话:

bool spl_autoload_register ([ callback $autoload_function ] )

将函数注册到SPL __autoload函数栈中,如果该栈中的函数尚未激活,则激活它们,貌似他么指向同一个堆栈,效率上都是大哥二哥的问题.

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表