最模板 - 外贸网站建设,外贸网站模板

最模板

当前位置: 首页 > 建站教程 > php教程 >

PHP autoload实现自动加载类

时间:2014-06-09 16:40来源: 作者: 点击:
autoload机制可以使得PHP程序有可能在使用类时才自动包含类文件,而不是一开始就将所有的类文件include进来,这种机制也称为lazy loading。 下面是使用autoload机制加载Person类的例子,代码如下: /*aut

autoload机制可以使得PHP程序有可能在使用类时才自动包含类文件,而不是一开始就将所有的类文件include进来,这种机制也称为lazy loading。

下面是使用autoload机制加载Person类的例子,代码如下:

  1. /* autoload.php */     
  2. <?php      
  3. function __autoload($classname) {  
  4.   require_once ($classname . “class.php”);  
  5. }      
  6. $person = new Person(”Altair”, 6);  
  7. var_dump ($person);  
  8. ?>  

PHP的autoload机制的实现,要在PHP中实现自动加载类,那就要说到一个魔术方法了,__autoload();这是PHP5添加的自动加载类方法,只要定义了该函数,那么如果PHP运行到该类找不到时,就会根据__autoload的规则去寻找。

自己也规划一下,跟set_include_path和get_include_path来配合使用,使自动加载类更完善点,代码飙一下(模仿magento的),代码如下:

  1. $paths[] = BP . DS . ‘app’ . DS . ‘local’; 
  2. $paths[] = BP . DS . ‘app’ . DS . ‘base’; 
  3. $paths[] = BP . DS . ‘lib’; 
  4. $appPath = implode(PS, $paths); 
  5. set_include_path($appPath . PS . get_include_path()); 

这样就可以为PHP添加默认的类加载环境,这里只是把路径添加到了PHP环境,如果还要继续添加规则,可以再定义__autoload函数,不过我这里是对象使用的,就换了一种方法:spl_autoload_register方法,下面是自己根据magento的规则,自己弄了一套,其实跟magento差不多,代码如下:

  1. class Autoload { 
  2. /** 
  3. * 自身对象 
  4. * 
  5. */ 
  6. protected static $_instance = null; 
  7. public function __construct() { 
  8. /* 
  9. * 实例化自身 
  10. * 
  11. */ 
  12. public static function instance() { 
  13. if (null == self::$_instance) { 
  14. self::$_instance = new self(); 
  15. return self::$_instance
  16. /** 
  17. * 
  18. * 注册自动加载函数 
  19. */ 
  20. public static function register() { 
  21. spl_autoload_register(array(self::instance(), ‘autoload’)); 
  22. /* 
  23. * 
  24. * 自动加载类 
  25. */ 
  26. public function autoload($class) { 
  27. if (!is_string($class)) { 
  28. return
  29. $classFile = str_replace(‘ ‘, DS, ucwords(str_replace(‘_’, ‘ ‘, $class))); 
  30. $classFile .= ‘.php’; 
  31. return include $classFile
(责任编辑:admin)
------分隔线----------------------------
栏目列表
推荐内容