PHP类的自动加载以及自定义自动加载函数

类的自动加载函数是个魔术方法,这个函数不需要调用是自动会加载调用的,PHP体系内部提供的方法,__ aotuload(),使用形式为:



注意:

  自动这个加载函数只能加载某一个目录路径的类文件,如果需要加载其他目录下面的类文件的时候就需要自定义加载函数了

spl_autoload_register(“函数名”) 先提前声明定义,然后再写对应的函数名中的,和自动加载函数形式类似:

//先声明一个函数名,提前告知系统将有 个自动加载函数要自己书写
spl_autoload_register("autoload1");
spl_autoload_register("autoload2");

function autoload1($className){
    $file="目录".$className.".class.php";
    
    if(file_exits($file)){  // 在这里做了个判断,file_exits()是判断文件或目录是否存在,如果不存在则提示,存在则直接加载
     require $file;
        }else{
            echo "需要加载的类文件不存在!!!";
        }


      //加载某个目录下面的类文件 (.class.php为文件后缀)
}

function autoload2($className){
  $file2="目录".$className.".class.php";
  if(file_exits($file)){  
     require $file2;
        }else{
            echo "需要加载的类文件不存在!!!";
        }
}

当用到这两个目录中的类文件的类的时候,这两个函数就会自动调用,用不到类的时候则不运行,给内存空间也省了许多地方

也可以直接把这两个函数直接封装进一个自定义加载类方法中去,可以实现多个类的自动加载,方法如下:

$file1="./class/".$className."tool.php";
$file2="./file/".$className."tool.php";
$file3="./exe/config/".$className.".php";
// 定义的路经变量
spl_autoload_resgister("autoload");
//注册一个函数名为autoload的 自定义自动加载类的函数
function autoload($className){
    if(file_exits($file1)){ // 如果这个类名在这个文件里面,则加载这个file1文件,下方两个同理
//$className 这个类 的文件 在这个file1路经中能找到这个对应的文件 所以可以加载   
        require_once $file1;
    }else if(file_exits($file2)){
        require_once $file2;
    }else if(file_exits($file3)){
        require_once $file3;
    }


}

 

你可能感兴趣的:(php,php的扩大化技术)