轻源码

  • QingYuanMa.com
  • 全球最大的互联网技术和资源下载平台
搜索
猜你喜欢
查看: 4378|回复: 1
打印 上一主题 下一主题

几个php中类的自动加载的方法的实例详解

[复制链接]

0

主题

0

帖子

1万

积分

钻石会员

Rank: 8Rank: 8

积分
17424
QQ
跳转到指定楼层
楼主
发表于 2020-3-15 11:30 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本篇文章主要介绍了PHP中类的自动加载的方法。类的自动加载是指在外面的页面中并不需要去“引入”类文件,但是程序会在需要的时候动态加载需要的类文件。

类的自动加载是指,在外面的页面中,并不需要去“引入”类文件,但是程序会在需要的时候动态加载需要的类文件。

方法1:使用autoload魔术

当程序需要某个类时,就会去调用该函数,该函数我们需要自己去定义并在其中写好加载类文件的通用语句。

<?php
    //需要类是自动调用,而且会传进来一个类名,这个案例的文件名为21A.class.php,类名为A
     function autoload($className){
      require "./21".$className.".class.php";
    }
    $o1 = new A();
    $o1->v1 = 10;
    echo "<br/>v1:".$o1->v1;
  ?>

方法2:使用spl_autoload_register函数

该函数的作用是生命多个可以用来代替autoload函数作用的函数,语法如下:spl_autoload_regist("函数名1");如果用spl_autoload_register,autoload就失效了。

<?php
    //注册两个用于自动加载的函数名
    spl_autoload_register('auto1');
    spl_autoload_register('auto2');
    function auto1($className){
      $file = "./21".$className.".class.php";
      if(file_exists($file)){
        require "./21".$className.".class.php";
      }
    }
    function auto1($className){
      $file = "./22".$className.".class.php";
      if(file_exists($file)){
        require "./22".$className.".class.php";
      }
    }
    //如果需要一个雷,但这个页面还没有记载,就会依次调用auto1和auto2,知道找到该类文件并加载
  ?>

再一个例子:

这里autoload 可兼容以下格式:

Cache_File_Json
class_xxx.php
xxx.class.php
xxx.php

如下:

function autoload($className){
 $dirs=explode('_',$className);
 $fileName=array_pop($dirs);
 //print_r($dirs);
 $filePath=$fileName;
 if(is_array($dirs) && (count($dirs) > 0)){
  //echo '
---
'; 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;
}

分享到:  QQ好友和群QQ好友和群
收藏收藏
回复

使用道具 举报

0

主题

20

帖子

1万

积分

钻石会员

Rank: 8Rank: 8

积分
17004
QQ
沙发
发表于 2022-6-9 21:35 | 只看该作者
下载歌曲不收费的软件
回复

使用道具 举报

轻源码让程序更轻更快

QingYuanMa.com

工作时间 周一至周六 8:00-17:30

侵权处理

客服QQ点击咨询

关注抖音号

定期抽VIP

Copyright © 2016-2021 https://www.171739.xyz/ 滇ICP备13200218号

快速回复 返回顶部 返回列表