0

Hy there I am trying to include bulk files from a directory into my php file. like I have 10 php files in a directory called models. instead of loading one by one, I am trying to load all files in the directory. I have found a solution to it as use of spl_autoload_register function. when I run the code, it says class not found.

index.php Code

$directories = array(
    BASE_DIR.DIRECTORY_SEPARATOR.'middlewares'.DIRECTORY_SEPARATOR,
);

function my_autoload_function ($classname){
    global $directories;
    foreach($directories as $directory){
        if(file_exists($directory.$classname.".php")){
            require_once($directory.$classname.".php");
        }
    }
}
spl_autoload_register('my_autoload_function', true);
require_once BASE_DIR.DIRECTORY_SEPARATOR."app.php";

$app = new App();

$app->init_app();

app.php code

class App{
    public function __construct(){

    }

    public function init_app(){
        $header = new HeadersMiddleWare();
        $parts = explode("/",$_SERVER['REQUEST_URI']);
        print_r($parts);
    }
}

.htaccess

RewriteEngine On
RewriteRule . index.php
Options -MultiViews

When run the application, I have the following issue:

Fatal error: Uncaught Error: Class "HeadersMiddleWare" not found in /var/www/html/app.php:10 Stack trace: #0 /var/www/html/index.php(43): App->init_app() #1 {main} thrown in /var/www/html/app.php on line 10

my directory structure is as follows:

_ middlewares
  |_ headers.php (headermiddleware class)
_ .htaccess
_ index.php
_ app.php

Looking for solutions and suggestions please.

Regards.

Asad Mehmood
  • 292
  • 2
  • 10
  • 20
  • Make sure there is no typo (singlular/plural) and case sensitiveness. – Markus Zeller Apr 20 '23 at 17:20
  • Please have a look at [this](https://stackoverflow.com/questions/7651509/what-is-autoloading-how-do-you-use-spl-autoload-autoload-and-spl-autoload-re) answer. this method is easier.. moreover you should avoid using ```DIRECTORY_SEPARATOR``` as its OS dependent and on linux/unix it will produce ```/``` on windows it will produce ```\``` – Anant V Apr 20 '23 at 17:56
  • Unless there's a typo I haven't spotted, the most obvious reasons are that the path is wrong or that the global variable is not yet defined when you read it. Set up a step debugger or at least `var_dump()` your variables. – Álvaro González Apr 21 '23 at 08:29

0 Answers0