将PHP __autoload(不建议使用的方法)替换为spl_autoload_register

时间:2017-06-20 17:10:48

标签: php spl-autoload-register

如何更改此代码以使用新的spl_autoload_register函数而不是弃用的方法__autoload

我的代码(正常运行):

<?php
require_once(ROOT.DS.'config'.DS.'config.php');

function __autoload($class_name) {
    $lib_path = ROOT.DS.'lib'.DS.strtolower($class_name).'.class.php';
    $controller_path = ROOT.DS.'controller'.DS.str_replace('controller', '', strtolower($class_name)).'.controller.php';
    $model_path = ROOT.DS.'models'.DS.strtolower($class_name).'.php';

    if (file_exists($lib_path)){
        require_once($lib_path);
    }elseif (file_exists($controller_path)){
        require_once($controller_path);
    }elseif (file_exists($model_path)){
        require_once($model_path);
    }else {
        throw new Exception("failed to include class named:".$class_name);
    }

}

我尝试将其更改为:

<?php
require_once(ROOT.DS.'config'.DS.'config.php');
spl_autoload_register(function ($class_name) {
    $lib_path = ROOT.DS.'lib'.DS.strtolower($class_name).'.class.php';
    $controller_path = ROOT.DS.'controller'.DS.str_replace('controller', '', strtolower($class_name)).'.controller.php';
    $model_path = ROOT.DS.'models'.DS.strtolower($class_name).'.php';

    if (file_exists($lib_path)){
        require_once($lib_path);
    }elseif (file_exists($controller_path)){
        require_once($controller_path);
    }elseif (file_exists($model_path)){
        require_once($model_path);
    }else {
        throw new Exception("failed to include class named:".$class_name);
    }

});

但是我收到了一个错误:

致命错误:未捕获错误:/srv/http/mvc/config/config.php:3中找不到类'Config'堆栈跟踪:#0 /srv/http/mvc/lib/init.php(2):require_once( )#1 /srv/http/mvc/webroot/index.php(6):在/ srv / http / mvc / config中抛出require_once('/ srv / http / mvc / l ...')#2 {main}第3行的/config.php

0 个答案:

没有答案
相关问题