spl_autload_register PHP not including files - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Friday, April 21, 2023

spl_autload_register PHP not including files

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.



source https://stackoverflow.com/questions/76066700/spl-autload-register-php-not-including-files

No comments:

Post a Comment