Search code examples
phpclassdirectory-structurespl-autoload-register

spl_autoload_register() in different directories


I have a file that auto loads each of my classes. This is what it contains:

spl_autoload_register(function($class){
    require_once 'classes/' . $class . '.php';
});
require_once 'functions/sanitize.php';
require_once 'functions/hash.php';

But when I require_once this file from another php file that is inside my ajax folder, it will try looking for the classes, the function will look from my classes with the path: main_folder/ajax/classes instead of just main_folder/classes.

Does anyone know how to fix this?

FIX:

spl_autoload_register(function($class){
    if (file_exists('classes/' . $class . '.php')) {
       require_once 'classes/' . $class . '.php';
    }
    elseif (file_exists('../classes/' . $class . '.php')) {
       require_once '../classes/' . $class . '.php';
    }
    elseif (file_exists('../../classes/' . $class . '.php')) {
       require_once '../../classes/' . $class . '.php';
    }

Solution

  • You should simple use this function just once - in the main file (usually index.php) and not in another files.

    However if it's not possible (but I don't see any reason when could it be not possible) you can change it for example that way:

    spl_autoload_register(function($class){
        if (file_exists('classes/' . $class . '.php')) {
           require_once 'classes/' . $class . '.php';
        }
        elseif (file_exists( $class . '.php')) {
           require_once $class . '.php';
        }
    });