How can I change this code to use new spl_autoload_register function instead the deprecated method __autoload?
My code(works properly):
<?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);
}
}
I tried to change it to:
<?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);
}
});
But I'm getting an error:
Fatal error: Uncaught Error: Class 'Config' not found in /srv/http/mvc/config/config.php:3 Stack trace: #0 /srv/http/mvc/lib/init.php(2): require_once() #1 /srv/http/mvc/webroot/index.php(6): require_once('/srv/http/mvc/l...') #2 {main} thrown in /srv/http/mvc/config/config.php on line 3