嗨,我正在为吉他和弦开发一个库.在库中的一些文件中我有这样的东西:
require_once "lib/GuitarChord.php";
require_once "lib/Chord.php";
require_once "lib/Key.php";
require_once "lib/Tuning.php";
Run Code Online (Sandbox Code Playgroud)
我怎样才能让这个库,所以它并不需要知道其中的其他库文件?
这样一个人可以在任何目录中拥有库文件?
编辑:删除了第二个问题.
为这些类可能的所有位置创建自动加载器.
例如:
//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');
Run Code Online (Sandbox Code Playgroud)
然后,如果你要加载的Chord类,你知道这是你的lib文件夹,自动加载器就做好了你,当你这样做:
new Chord();
Run Code Online (Sandbox Code Playgroud)
您可以附加许多不同的自动加载器回调 spl_autoload_register