PHP autoloader duplicate path

32 Views Asked by At

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.

1

There are 1 best solutions below

0
Moshe Gross On

The $class that's passed into the autoloader is the class including the namespace.

So in your case the value of $class is classes\account\RegisterAccount

So you can scrap this part

$directories = [
    __DIR__ .  "/classes/account/",
    __DIR__ .  "/classes/database/",
];

Also, you don't have to return true or false as spl_autoload_register returns true if it manages to load the class, and false otherwise.

So you function should look like this

function myAutoLoader($class){
    $fullPath = __DIR__ . '/' .  str_replace('\\', '/', $class) . '.php';
    if(file_exists($fullPath)) {
        require_once $fullPath;
    }
}