i want to learn autoloader in PHP but i loader duplicate my path to my files and its not working.
<?php
function myAutoLoader($class){
$directories = [
__DIR__ . "/classes/account/",
__DIR__ . "/classes/database/",
];
$extension = ".php";
foreach ($directories as $directory){
$fullPath = $directory . str_replace('\\', '/', $class) . $extension;
var_dump($fullPath);
if(file_exists($fullPath)) {
require_once $fullPath;
return true;
}
}
return false;
}
spl_autoload_register('myAutoLoader');
and my Classes, were i want get path:
<?php
namespace controllers;
use classes\account\RegisterAccount;
require_once __DIR__ . "/../includes/autoloader.php";
class RegisterController extends RegisterAccount
but path its duplicate: string(94) "C:\xampp\htdocs\reservationSystem\includes/classes/account/classes/account/RegisterAccount.php" string(95)
my directory structure is :
project/
├── classes/
│ ├── account/
|
___RegisterAccount.php
│ └── database/
│ └── Connect.php
└── includes/
└── autoloader.php
I searched for answers on youtube and sof but, did not find a solution.
The
$classthat's passed into the autoloader is the class including the namespace.So in your case the value of
$classisclasses\account\RegisterAccountSo you can scrap this part
Also, you don't have to return true or false as
spl_autoload_registerreturns true if it manages to load the class, and false otherwise.So you function should look like this