使用 spl 自动加载寄存器时出错

Error On Using spl autoload register

这在 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

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

嗯,您使用的 spl_autoload_register 功能不正确。

当您尝试创建不存在的 class 时,将调用自动加载函数。

正确的方法是将文件命名为文件中的 class 并添加一个结尾,如 .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();