0

Autoloader code:

<?php
spl_autoload_register('myAutoLoader');

function myAutoLoader($className){
    $path = "/classes/";
    $extension = ".class.php";
    $fullPath = $path . $className . $extension;
    echo $fullPath;
    if(file_exists($fullpath)){
        require $fullPath;
    }
}
?>

And it is throwing error, that class is not found for some reason. I even tried to print out the fullpath variable, and it matches the path, in which class is located. File structure: https://prnt.sc/17v3qsk Fullpath value: "/classes/DatabaseConnect.class.php"

Sample index.php code that I am trying to use it in:

<?php
include 'includes/autoloader.inc.php';
$dbConnect = new DatabaseConnect('127.0.0.1','root','','test');

if($dbConnect->connect_errno){
    die("Failed to connect to the database: " . $dbConnect->connect_error);
}
echo 'connected successfully';
?>

EDIT 1:

<?php
spl_autoload_register('myAutoLoader');

function myAutoLoader($className){
    $path = "/classes/"; // <-- Notice the ".."
    $extension = ".class.php";
    $fullPath = $_SERVER["DOCUMENT_ROOT"] . $path . $className . $extension;
    echo $fullPath;
    if(file_exists($fullpath)){
        require $fullPath;
    }
}
?>
ddd
  • 3
  • 3
  • Does this answer your question? [What is Autoloading; How do you use spl\_autoload, \_\_autoload and spl\_autoload\_register?](https://stackoverflow.com/questions/7651509/what-is-autoloading-how-do-you-use-spl-autoload-autoload-and-spl-autoload-re) – KhorneHoly Jul 01 '21 at 15:43
  • That path can't be right. Project root is never in the file system root, not even in Docker setups. – Álvaro González Jul 01 '21 at 16:11

1 Answers1

0

The built $fullPath will look like this: /classes/DatabaseConnect.class.php. Now the problem is that this is an absolute path, not relative to the project root directory.

In your case, because the autoloader.inc.php is in the includes folder, which in turn is on the same level with the classes folder, the following should work:

<?php
spl_autoload_register('myAutoLoader');

function myAutoLoader($className){
    $path = __DIR__ . "/../classes/"; // <-- Notice the ".."
    $extension = ".class.php";
    $fullPath = $path . $className . $extension;
    echo $fullPath;
    if(file_exists($fullpath)){
        require $fullPath;
    }
}
?>
Zoli Szabó
  • 4,366
  • 1
  • 13
  • 19
  • Thank you for your reply, but it does not solve the issue. It gives the correct path with document root(see the edit 1) and I can even open it up in the windows explorer – ddd Jul 01 '21 at 16:57
  • I've updated the code with a newer version of building the path. Please check it out. – Zoli Szabó Jul 01 '21 at 18:20