【问题标题】:__autoload() Doesn't seem to do anything in PHP__autoload() 在 PHP 中似乎没有做任何事情
【发布时间】:2011-02-03 21:27:20
【问题描述】:

我正在运行最新版本的 XAMPP,但 autoload() 似乎无法正常工作。我几乎用 PHP 手册中的自动加载替换了我之前的自动加载,但无济于事。

在输入了几个 echo 和 die() 之后,我得出结论,__autoload 根本没有被调用。

class Main
{

    var $config_data;

    function __autoload($class_name) {
        echo "hello.";
        // If the file exists, require it
        if (file_exists(SYSTEMDIR.$class_name.".".EXT)) {
            echo 'Autoloader: The class exists.';
            (require_once(SYSTEMDIR.$class_name.".".EXT))
                or die("I tried to autoload class $class_name, but it failed! =(");
        } else {
            // The file didn't even exist. Die.
            die("I was going to autoload class $class_name, but it didn't exist! =(");
        }

    }

    /*
     * Function __construct
     * @param datatype variable description
     * @return datatype description
     */
   function __construct(/* $arg */) {
       //Load the config

       $this->config = new Config;

       //Load the uri class:
       $this->uri = new Uri;
   }

}

它不输出位于 __autoload() 最顶部的“hello”。

唯一的输出是:

致命错误:找不到类“配置” 在 E:\xampplite\htdocs\system\Main.php 在第 84 行

【问题讨论】:

  • 你能把__autoload放到一个类里面吗?您想将自动加载用作一般功能,不是吗?。

标签: php xampp autoload


【解决方案1】:

AFAIK 函数__autoload 必须在类外定义。如果你想在类中实现自动加载功能,你应该使用回调和spl_autoload_register

【讨论】:

  • 这也是首选方式,因为其他库可能使用自己的自动加载器。不允许使用两个具有相同名称的函数,如果有人将自动加载器注册到 spl_autoload_register(),则不会再调用 __autoload()-函数。
【解决方案2】:

那是因为您声明了 Main->__autoload() 函数(即类方法)而不是全局 __autoload()

【讨论】:

    【解决方案3】:

    __autoload 不参加 课程。它用于包含类所在的文件。

    您需要在初始脚本中添加一个自动加载函数才能让它执行任何操作。

    【讨论】:

    • 谢谢,我在 PHP 手册中没有看到任何地方提到过! -.- 看来我还要等七分钟才能选择答案……
    猜你喜欢
    • 2016-04-09
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 2019-11-26
    • 2019-12-08
    • 1970-01-01
    • 2020-12-21
    • 2023-04-06
    相关资源
    最近更新 更多