Spl_autoload_register not loading file


#1

Hello,
I have an issue with my autoload not working correctly. I may be missing something, but for the life of me I do not know what. My errorlog states: PHP Fatal error: Uncaught Error: Class ‘user\\full_name’ not found in /my/file/path/to/index.php.

In index.php I am calling my class with namespace as:
$test = new file\class_name();

My autoload function/method is as so:

spl_autoload_register('Autoloader::ClassLoader');

class Autoloader
{
public static function ClassLoader($class)
    {
            $classFile = str_replace('\\', DIRECTORY_SEPARATOR, $class);
            $file_path = __ROOT__ . '/include/class/' . $classFile . '.php';

            if (is_file($file_path) && file_exists($file_path))
            {
                    include_once $file_path;
                    echo $file_path; // Testing that I get an output in index.php. 
                                    // and I do.
            }
    }
}

Any direction on what is incorrect would be greatly appreciated. I have been looking around on the internet to get this far, but cannot find a solution to why this does not work for me. $file_path echos out correctly for the file path, but in my error message I do not know why my Class has \\ when I have str_replace to replace \ . If I str_replace \\\\ to replace the double \ from the namespace I still get the same error, but the echo in the function does not return in index.php.

Thank you,

Leavii


#2

First, I would recommend you use PSR-4 Autoloading.

The $file_path line has a syntax error. It happens easily when you do unnecessary escaping gymnastics. If you had error reporting turned on PHP would have told you there was a problem. Change it to

"__ROOT__ /include/class/$classFile.php";

When I run (with return added before $file_path)

$v = new Autoloader();
echo $v->ClassLoader('myfile');

I get the path

__ROOT__ /include/class/myfile.php

No idea what ROOT is defined as.


#3

Thanks for the reply @benanamen. I will read up on PSR-4 Autoloading as I have never heard of this. I have ROOT defined as $_SERVER[‘DOCUMENT_ROOT’] so I can get an absolute path easily.

I have tried “” instead of breaking it all apart in ’ ', and concatenating but I still get this error in my error.log. I do have error reporting in PHP my error is included above. Or do i need to catch something to have it logged?

I do not receive a syntax error in the set of $file_path, and I am not seeing it even now(?). Yes it is messy, and not what I normally do, but it works.

Currently if I return $file_path it gives the correct path to my Class file. I also get the expected output when I return $classFile.