Search code examples
phpspl-autoload-register

spl_autoload_register fails when load classes


So the structure of my project is the following:

- Project
   - php
      - classes
          - Config.php
          - DB.php
      - core
          - init.php
      - index.php

In my core/init.php file, I use spl_autoload_register() to load the different classes:

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

And for test reasons, in index.php, I require my init.php file and try a method of my DB class:

require_once 'php/core/init.php'; 
$_db = DB::getInstance();

But I just get nothing. I am sure the issue is the PHP because when I only have html in index.php, everything's work.

Where is the issue? I assume it is from spl_autoload_register() which, somehow fail to work.


Solution

  • Change your autoloader to this:

    spl_autoload_register(function ($class) {
        require_once __DIR__ . '/../classes/' .$class. '.php';
    });
    

    So are you sure that it includes the file from the correct location.