How to use spl_autoload_register for multiple directories in PHP

Viewed 36

Follow the code for the autoload class in multiple paths.

This question is to remedy php users for correct usage of spl in various directories After a long time I elaborated this to sanitize my code.

    spl_autoload_register(function($class){
    $paths = array(
        'classes/',
        'engine/'
    );

    foreach($paths as $path){

        $file = LIBRARY . $path . str_replace('\\', '/', strtolower($class)) . '.php';

        if(file_exists($file)){
            $files = array($file);
        }
    }

    foreach($files as $file){
        if(is_file($file)){
            include_once($file);
            return true;
        }else{
            return false;
        }
    }
    
});
0 Answers
Related