当前位置:首页 > PHP教程 > php面向对象 > 列表

php spl_autoload_register与__autoload方法详解

发布:smiling 来源: PHP粉丝网  添加日期:2014-05-20 15:38:35 浏览: 评论:0 

php spl_autoload_register与__autoload方法详解

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

  1. function my_own_loader($classname
  2.     $class_file = strtolower($classname).".php"
  3.     if (file_exists($class_file)){ 
  4.         require_once($class_file); 
  5.     } 
  6.  
  7. spl_autoload_register("my_own_loader"); 
  8.  
  9. $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.     $class_file = strtolower($classname).".php"
  3.     if (file_exists($class_file)){ 
  4.         require_once($class_file); 
  5.     } 
  6.  
  7. spl_autoload_register("my_own_loader"); 
  8.  
  9. $a = new A(); 

第二种类式:class Loader

  1.     public static 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. // 通过数组的形式传递类和方法的名称 
  10. spl_autoload_register(array("my_own_loader","Loader")); 
  11.  
  12. $a = new A(); 

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

支持版本:PHP 5 >= 5.1.2

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

bool spl_autoload_register ([ callback $autoload_function ] )

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

Tags: spl_autoload_register __autoload

分享到: