PHP经验——autoload当程序实例化的类不存在时被启发

__autoload的功能是当程序中要使用的类不存在时,该函数将被调用。

在面向对象的程序设计中,这个函数很有用,可以使函数智能加载某些文件与类,实现文件的动态包含、类的动态引用。

下边是一个实例:

<?php
function __autoload($class_name)
 {
     $class_name = str_replace('-', '', $class_name);
     $dirs = array('/plugins/'.$class_name.'/', '/includes/', '/includes/interface/', '/includes/to/', '/includes/to/device/', '/includes/os/', '/includes/mb/', '/includes/plugin/', '/includes/xml/', '/includes/web/', '/includes/error/', '/includes/js/', '/includes/output/', '/includes/ups/');
     
     foreach ($dirs as $dir) {
         if (file_exists(APP_ROOT.$dir.'class.'.$class_name.'.inc.php')) {
             include_once APP_ROOT.$dir.'class.'.$class_name.'.inc.php';
             return;
         }
     }
 }
 ?>

实例中的 参数 $class_name是自动捕获的类名,可以当做函数形参。

posted @ 2012-10-04 09:51  小 伍  阅读(836)  评论(0编辑  收藏  举报