加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

制作一个php库,如何让它独立?

发布时间:2020-12-13 13:18:54 所属栏目:PHP教程 来源:网络整理
导读:嗨,我正在为吉他和弦开发一个库.在库中的一些文件中我有这样的东西: require_once "lib/GuitarChord.php";require_once "lib/Chord.php";require_once "lib/Key.php";require_once "lib/Tuning.php"; 如何创建此库,以便不需要知道其他库文件的位置? 这样一
嗨,我正在为吉他和弦开发一个库.在库中的一些文件中我有这样的东西:
require_once "lib/GuitarChord.php";
require_once "lib/Chord.php";
require_once "lib/Key.php";
require_once "lib/Tuning.php";

如何创建此库,以便不需要知道其他库文件的位置?

这样一个人可以在任何目录中拥有库文件?

编辑:删除了第二个问题.

为这些类可能的所有位置创建自动加载器.

例如:

//AUTOLOADER
function class_autoloader($class) {

   // presumes classes are in './classes'
   $folders = array(
     './','./../','./../../'  
   );
   $directories = array(
     'classes','lib',''
   );
   $dir = dirname(__FILE__);
   $theClass = '/' . $folderedClass . '.php';


   foreach($folders as $folder){
       foreach($directories as $directory){
           $theInclude = $dir.$folder.$directory.$theClass;

           if (file_exists($theInclude) && include_once($theInclude)) {
              return TRUE;
           } 
       }
   }

  trigger_error("The class '$class' or the file '$theClass' failed to spl_autoload ",E_USER_WARNING);

  return FALSE;
}

spl_autoload_register('class_autoloader');

然后,如果你想加载Chord类并且你知道它在你的lib文件夹中,那么当你这样做时,自动加载器将为你完成工作:

new Chord();

您可以使用spl_autoload_register附加许多不同的自动加载器回调

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读