phpautoloadspl-autoload-register

Fatal error: Cannot redeclare spl_autoload_register() with simple php blog


I used a simple php blog platform for my website many years ago, this used the old __autoload function. I recently had to migrate hosts and they use a newer version of php so that function no longer works. I tried replacing __autoload with spl_autoload_register but I get the error in the title. I am not skilled in php and I can't figure out how to resolve this myself. Below is the code from my config.php file.

//load classes as needed
function spl_autoload_register($class) {
   
   $class = strtolower($class);

    //if call from within assets adjust the path
   $classpath = 'classes/class.'.$class . '.php';
   if ( file_exists($classpath)) {
      require_once $classpath;
    }   
    
    //if call from within admin adjust the path
   $classpath = '../classes/class.'.$class . '.php';
   if ( file_exists($classpath)) {
      require_once $classpath;
    }
    
    //if call from within admin adjust the path
   $classpath = '../../classes/class.'.$class . '.php';
   if ( file_exists($classpath)) {
      require_once $classpath;
    }       
     
}

Solution

  • spl_autoload_register() is an existing PHP function which you cannot redefine. Try to use it like this:

    function my_autoloader($class) {
       
       $class = strtolower($class);
    
        //if call from within assets adjust the path
       $classpath = 'classes/class.'.$class . '.php';
       if ( file_exists($classpath)) {
          require_once $classpath;
        }   
        
        //if call from within admin adjust the path
       $classpath = '../classes/class.'.$class . '.php';
       if ( file_exists($classpath)) {
          require_once $classpath;
        }
        
        //if call from within admin adjust the path
       $classpath = '../../classes/class.'.$class . '.php';
       if ( file_exists($classpath)) {
          require_once $classpath;
        }       
         
    }
    
    spl_autoload_register('my_autoloader');
    

    I left out the rest of the code, since it is not really what the question is about.

    For more information see: spl_autoload_register()