Why my autoloader function cannot find the specific class

277 views Asked by At

here is my folder structure:

-classes
  -controller
     -ProductCtrl.php
  -model
  -view
-includes
  -components
  -autoload.inc.php
-pages
  -home.php
  -add-product.php
-index.php

this is my autoloader function:

spl_autoload_register(function ($class) {
$str = str_replace("\\", "/", $class);
$file = $str.".php";

// if the file exists, require it
if (file_exists($file)) {
    require $file;
}
});

Index.php

<?php
 require "includes/autoload.inc.php";

 //home page
 include "pages/Home.php";

Now I can access the ProductCtrl class from home.php which is in index.php, but whenever I try to accesss the same class in add-product.php file it gives me an error saying:

Fatal error: Uncaught Error: Class "classes\controller\ProductCtrl" not found in 
project_directory\pages\add-product.php

Note: I have used namespace in every class containing the folder structure.

1

There are 1 answers

1
hakre On

The file most likely does not exist and therefore the class remains undefined.

If you specify a base-path, it is more explicit and might solve it already:

$file = __DIR__ . '///..///' . $str . ".php";
trigger_error("looking for file: '$file'");

Also check the error log for notices showing which file paths are processed by your auto-loader (by the trigger_error logging, you can remove it later).