0

我正在实现一个自动加载器类,但它不工作。下面是自动加载器类(灵感来自php.net 上的这个页面):

class System
{
    public static $loader;

    public static function init()
    {
        if (self::$loader == NULL)
        {
            self::$loader = new self();
        }

        return self::$loader;
    }

    public function __construct()
    {
        spl_autoload_register(array($this, "autoload"));
    }

    public function autoload($_class)
    {
        set_include_path(__DIR__ . "/");
        spl_autoload_extensions(".class.php");
        spl_autoload($_class);
print get_include_path() . "<br>\n";
print spl_autoload_extensions() . "<br>\n";
print $_class . "<br>\n";
    }
}

调用自动加载器的代码在这里:

<?php
error_reporting(-1);
ini_set('display_errors', 'On');

require_once __DIR__ . "/system/System.class.php";

System::init();

$var = new MyClass(); // line 9

print_r($var);
?>

和错误信息:

/home/scott/www/system/
.class.php
MyClass
Fatal error: Class 'MyClass' not found in /home/scott/www/index.php on line 9

正在命中自动加载功能,文件 MyClass.class.php 存在于包含路径中,我可以通过将代码更改为以下内容来验证:

<?php
error_reporting(-1);
ini_set('display_errors', 'On');

require_once __DIR__ . "/system/System.class.php";
require_once __DIR__ . "/system/MyClass.class.php";

System::init();

$var = new MyClass();

print_r($var);
?>

print_r($var);返回对象并且没有错误。

有什么建议或指示吗?

4

1 回答 1

0

spl_autoload 的文档页面所述,在查找类文件之前,类名是小写的。

所以,解决方案 1 是小写我的文件,这对我来说并不是一个可以接受的答案。我有一个名为 MyClass 的类,我想把它放在一个名为 MyClass.class.php 的文件中,而不是放在 myclass.class.php 中。

解决方案 2 是根本不使用 spl_autoload:

<?php
class System
{
    public static $loader;

    public static function init()
    {
        if (self::$loader == NULL)
        {
            self::$loader = new self();
        }

        return self::$loader;
    }

    public function __construct()
    {
        spl_autoload_register(array($this, "autoload"));
    }

    public function autoload($_class)
    {
        require_once __DIR__ . "/" . $_class . ".class.php";
    }
}
?>
于 2014-07-11T19:11:03.077 回答