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

时间:2015-03-22 19:48:18

标签: php 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

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

1 个答案:

答案 0 :(得分: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();