我正在使用spl_autoload_register()函数来包含所有文件。我想要的是,任何具有扩展.class.php或.php的类都将直接包括。我创建了下面的类,注册了两个不同的函数,所有功能都很好,但是。
我认为有一些方法,所以我只需要注册一个函数就可以将两个扩展合并在一起。
请看一下我的功能,告诉我我错过了什么。
我的文件夹结构
project
-classes
-alpha.class.php
-beta.class.php
-otherclass.php
-includes
- autoload.php
-config.inc.php // define CLASS_DIR and include 'autoload.php'autoload.php
var_dump(__DIR__); // 'D:\xampp\htdocs\myproject\includes'
var_dump(CLASS_DIR); // 'D:/xampp/htdocs/myproject/classes/'
spl_autoload_register(null, false);
spl_autoload_extensions(".php, .class.php"); // no use for now
/*** class Loader ***/
class AL
{
public static function autoload($class)
{
$filename = strtolower($class) . '.php';
$filepath = CLASS_DIR.$filename;
if(is_readable($filepath)){
include_once $filepath;
}
// else {
// trigger_error("The class file was not found!", E_USER_ERROR);
// }
}
public static function classLoader($class)
{
$filename = strtolower($class) . '.class.php';
$filepath = CLASS_DIR . $filename;
if(is_readable($filepath)){
include_once $filepath;
}
}
}
spl_autoload_register('AL::autoload');
spl_autoload_register('AL::classLoader');注:对线路spl_autoload_extensions();没有影响。为什么?
我也读过这个博客,但不知道如何实现。
发布于 2012-07-26 07:13:23
你这样做没什么不对的。两种类文件的两种不同的自动加载程序都很好,但是我会给它们更多的描述性名称;)
注:线上
spl_autoload_extensions();不受影响。为什么?
这只会影响内置的自动加载spl_autoload()。
也许使用单个加载程序更容易
public static function autoload($class)
{
if (is_readable(CLASS_DIR.strtolower($class) . '.php')) {
include_once CLASS_DIR.strtolower($class) . '.php';
} else if (is_readable(CLASS_DIR.strtolower($class) . '.class.php')) {
include_once CLASS_DIR.strtolower($class) . '.class.php';
}
}你也可以忽略整个班级。
spl_autoload_register(function($class) {
if (is_readable(CLASS_DIR.strtolower($class) . '.php')) {
include_once CLASS_DIR.strtolower($class) . '.php';
} else if (is_readable(CLASS_DIR.strtolower($class) . '.class.php')) {
include_once CLASS_DIR.strtolower($class) . '.class.php';
}
});发布于 2012-07-26 07:07:23
也许这会有帮助:
http://php.net/manual/de/function.spl-autoload-extensions.php
杰里米·库克03-2010年9月06:46 对于任何使用此功能来添加自己的自动加载扩展的人来说,这是一个快速的注意事项。我发现,如果在不同的扩展(即'.php,.class.php')之间包含一个空格,则该函数将无法工作。为了使它发挥作用,我不得不删除扩展之间的空格(即。'.php,.class.php')。这在WindowsPHP5.3.3中进行了测试,我使用的是spl_autoload_register(),没有添加任何自定义的自动加载函数。 希望这能帮到别人。
https://stackoverflow.com/questions/11664083
复制相似问题