Can't using spl_autoload_register to load classes in PHP

48 views Asked by At

I just encountered an error while programming PHP. The thing is that I used spl_autoload_register inside the init.php file but could not load the classes inside the classes folder. I make sure that the classes inside the files in the classes folder have the same name as the file name. And if I don't use spl_autoload_register and include_once on each file, it works (I commented the included_once files manually). Please give me a solution. Here is my directory structure:

This is my project folder structure

Here is the code inside the init.php file:

<?php
include_once dirname(__DIR__) . "/inc/" . "config.php"; 


// include_once dirname(__DIR__) . "/classes/" . "database.php"; 
// include_once dirname(__DIR__) . "/classes/" . "user.php"; 
// include_once dirname(__DIR__) . "/classes/" . "student.php"; 

// Auto load class
spl_autoload_register(function ($class) {
    include_once dirname(__DIR__) . "/classes/" . strtolower($class) . ".php"; 
});
?>

I tried changing the available paths, but it didn't seem to work the way I wanted, I also thought maybe I had the wrong path

1

There are 1 answers

2
DinhChieu_73 On

I just discovered that when using spl_autoload_register you need to initialize an object for the program to actually load.