欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php类自动加载器实现方法

程序员文章站 2023-11-12 10:18:22
本文实例讲述了php类自动加载器实现方法。分享给大家供大家参考。具体如下: 这里autoload 可兼容以下格式: cache_file_json class_xx...

本文实例讲述了php类自动加载器实现方法。分享给大家供大家参考。具体如下:

这里autoload 可兼容以下格式:

cache_file_json
class_xxx.php
xxx.class.php
  xxx.php

php代码如下:

function __autoload($classname){
 $dirs=explode('_',$classname);
 $filename=array_pop($dirs);
 //print_r($dirs);
 $filepath=$filename;
 if(is_array($dirs) && (count($dirs) > 0)){
  //echo '\n---\n'; print_r($dirs);
  $dirpath='';
  foreach ($dirs as $dir){
   if($dir){
    $dirpath.=strtolower($dir).directory_separator;
   }
  }
  $filepath=$dirpath.$filename.'.php';
 }else {
  if( file_exists('class_'.$filename.'.php')){
   $filepath='class_'.$filename.'.php';
  }else {
   if( file_exists($filename.'.class.php')){
    $filepath=$filename.'.class.php';
   } else {
    $filepath=$filename.'.php';
   }
  } 
 }
 //var_dump($filepath);
 require $filepath;
}

希望本文所述对大家的php程序设计有所帮助。