Home > other >  PHP autoloader does not work in multiple files
PHP autoloader does not work in multiple files

Time:07-05

In my project I have the following directories (please see the image attached). For the project to work correctly, I have to include my autoloader.php file into two files: index.php and classes/FormController.php

When using my autoloader function that is illustrated below, the autoloader happens to be included only in index.php, but not in classes/FormController.php as well. I also tried using __DIR__ but it didn't help.

    spl_autoload_register('myAutoLoader');
    
    function myAutoLoader(string $className)
    {
    
        $path = ['classes/', null];
        $extension = '.php';
    
        foreach($path as $currentDirectory){
    
            $fullPath = $currentDirectory . $className . $extension;
    
            if(!file_exists($fullPath)){
                return false;
            }
    
            include_once $fullPath;

        }
    
    }

enter image description here

CodePudding user response:

You use return when it fails to find the class in the first path, so it never tries the second.

Consider something like:

    spl_autoload_register('myAutoLoader');
    
    function myAutoLoader(string $className)
    {
    
        $path = ['classes/', ''];
        $extension = '.php';
    
        $found = false;

        for ($idx = 0; !found && $idx < count($path); $idx  ) {

            $fullPath = $path[$idx] . $className . $extension;

            $found = file_exists($fullPath);

            if ($found) {
                include_once $fullPath;
            }
        }
    }

Edit to add:

If you're only ever going to be looking in those two directories, a loop is hardly necessary:

$fileName = $classname . $extension;

if (file_exists($fileName) {
    include_once $fileName;
} else if (file_exists('classes/' . $fileName) {
    include_once 'classes/' . $filename;
}
  •  Tags:  
  • php
  • Related