【问题标题】:Error On Using spl autoload register使用 spl 自动加载寄存器时出错
【发布时间】:2015-03-22 19:48:17
【问题描述】:

这在 init.php 上运行良好

include 'models/m_app.php';
include 'views/v_app.php';
include 'controllers/c_app.php';

spl_autoload_register() 不起作用

spl_autoload_register(function ($class) {
    include 'models/' . $class . '.class.php';
    include 'views/' . $class . '.class.php';
    include 'controllers/' . $class . '.class.php';
});

我收到类似

的错误
Warning: include(models/Model.class.php): failed to open stream: No such file or directory in C:\wamp\www\App\core\init.php on line 3
Warning: include(): Failed opening 'models/Model.class.php' for inclusion (include_path='.;C:\php\pear') in C:\wamp\www\App\core\init.php on line 3
Warning: include(views/Model.class.php): failed to open stream: No such file or directory in C:\wamp\www\App\core\init.php on line 4
Warning: include(): Failed opening 'views/Model.class.php' for inclusion (include_path='.;C:\php\pear') in C:\wamp\www\App\core\init.php on line 4
Warning: include(controllers/Model.class.php): failed to open stream: No such file or directory in C:\wamp\www\App\core\init.php on line 5
Warning: include(): Failed opening 'controllers/Model.class.php' for inclusion (include_path='.;C:\php\pear') in C:\wamp\www\App\core\init.php on line 5

你能告诉我为什么会这样吗?

【问题讨论】:

    标签: php spl-autoload-register


    【解决方案1】:

    好吧,您使用的 spl_autoload_register 函数不正确。

    当您尝试创建一个不存在的类时,会调用自动加载函数。

    正确的方法是将文件命名为文件中的类并添加类似 .class.php 的结尾:

    View.class.php
    Model.class.php
    Controller.class.php
    

    自动加载器:

    spl_autoload_register(function ($class) {
        set_include_path('views/' . PATH_SEPARATOR . 'controllers/' . PATH_SEPARATOR . 'models/');
        include $class . '.class.php';
    });
    

    并对其进行测试:

    $test1 = new Model();
    $test2 = new Controller();
    $test3 = new View();
    

    【讨论】:

    • 谢谢spl_autoload_register(function($class) { require_once 'classes/' . $class . '.php'; }); 在这里不起作用
    • 你能看看这个sample,让我知道它在这个例子中是如何工作的吗?
    • 那是因为它会寻找文件 core/classes/... 你需要添加 ../classes/ 或 /classes ;-)
    • 正如 Marc 所说,当您尝试实例化不存在的类时,将调用您注册到 spl 自动加载器的函数。包含命名空间的类名(如果存在)将传递给注册的自动加载函数。这意味着您必须使用传递的类名并找出文件+它的位置+自己包含它。到现在为止还挺好。在您在第一篇文章中分享的代码中至少有一个错误。您尝试从不同位置包含该文件三次。也没有文件存在检查。我建议再看看 php.net -> spl_autoload_regist
    猜你喜欢
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 2010-12-15
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    相关资源
    最近更新 更多