分享

PHP类的自动加载

 示且青春 2013-11-19

PHP类的自动加载__autoload && spl_autoload_register

通常我们写一个类如下:

a.php

  1. class A  
  2. {  
  3.     public function __construct()  
  4.     {  
  5.         echo "hello world!";  
  6.     }  
  7. }  

page.php

  1. require("a.php");  
  2. $a = new A();  

我们是通过手工引用某个类的文件来实现函数或者类的加载

但是当系统比较庞大,以及这些类的文件很多的时候,这种方式就显得非常不方便了

于是PHP5提供了一个::auotload::的方法

我们可通过编写该方法来自动加载当前文件中使用的类文件

page.php

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

这样,当使用类A的时候,发现当前文件中没有定义A,则会执行autoload函数,并根据该函数实现的方式,去加载包含A类的文件

同时,我们可以不使用该方法,而是使用我们自定义的方法来加载文件,这里就需要使用到函数

bool spl_autoload_register ( [callback $autoload_function] )

page.php

  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();  

实现的是同样的功能

自定义的加载函数还可以是类的方法

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

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多