使用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.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();