0

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
tereško
  • 58,060
  • 25
  • 98
  • 150
  • Check closure and how to pass variable to the scope. Anything outside of anonymous function will not be available inside unless you make closure. – anwerj Jun 20 '17 at 17:16
  • Register the autoloader before requiring the config. It seems the config needs a class to work. Also the autoloader function should not throw an exception, if it doesn't work PHP needs to try using other registered autoloaders and throwing an exception might prevent that. – apokryfos Jun 20 '17 at 17:17
  • i got it thankyou guys –  Jun 20 '17 at 17:22

0 Answers0