php - 制作一个php库,如何使其独立?

标签 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 附加许多不同的自动加载器回调

关于php - 制作一个php库,如何使其独立?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7437981/

相关文章:

php - 无法使用 ssh2_scp_recv 和 ssh2_scp_send 发送或接收文件

php - Laravel 4 中的通用访问器和修改器

php - 如何在 PHP 中生成多语言内容 Pdf

php - 为什么 "104"排在 "0000105"之前?

javascript - 如何将二维 PHP 数组编码为 JSON 数组以便在 JavaScript 中解码?

javascript - 谁能告诉我为什么我的导航不起作用?

php - Laravel 5.1 与多对多模型的 Eloquent 远距离关系

php - 在单元测试中模拟被测试的对象是不是很糟糕?

php - 在 $_SESSION 变量中缓存变量?

php - 小型应用程序的 Mysql 缩放