PHP – Autoloader Crashing When Model File Does Not Exist

Home Forums Bugs PHP – Autoloader Crashing When Model File Does Not Exist

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #1441
    Eugest Xhelollari
    Participant

    đź”´ Error

    Autoloader requires a file that may not exist
    ❌ Before (broken):

    spl_autoload_register(function($classname){
    require $filename = “../app/models/”.ucfirst($classname).”.php”;
    });

    What’s wrong: require will crash the entire application if the file doesn’t exist. When PHP tries to autoload a class that has no model file (like the built-in PDO class), it will throw a fatal error immediately.

    âś… After (fixed):

    spl_autoload_register(function($classname){
    // Use require_once only if the file actually exists, to prevent fatal crashes
    $filename = “../app/models/”.ucfirst($classname).”.php”;
    if(file_exists($filename)){
    require_once $filename;
    }
    });

    Why it’s fixed: Checking with file_exists() first means the autoloader only loads files that are actually there, and silently skips anything else — no crash.

Viewing 1 post (of 1 total)
  • You must be logged in to reply to this topic.