如何更改此代码以使用新的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