phpautoloadspl-autoload-register

php - autoload not working with static method


I using spl_autoload_register to autoload class like

My Structure

index.php
Module\Autoloader.php
Module\MyClass.php
Test\test.php

in index.php file

require_once ("Module\Autoloader.php");
use Module\MyClass;
include 'Test\test.php';

in Module\Autoloader.php file

class Autoloader {
        static public function loader($className) {
            $filename = __DIR__."/" . str_replace("\\", '/', $className) . ".php";
            echo $filename.'<br>';
            if (file_exists($filename)) {
                include($filename);
            }
        }
}
spl_autoload_register('Autoloader::loader');

in Module\MyClass.php file

namespace Module;
class MyClass {
    public static function run() {
        echo 'run';
    }
}

in Test\test.php file

MyClass::run();

But it has error

Fatal error: Uncaught Error: Class 'MyClass' not found in ..\Test\test.php

How to fix that thank


Solution

  • your issue is that you prepend __DIR__

    __DIR__ is based on where the file from which it gets called resides:

    __DIR__

    The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.

    http://php.net/manual/en/language.constants.predefined.php

    So because your autoloader routine resides in ./Module/

    __DIR__ will not return / when called from index.php but Module, making your finished classpath Module/Module/MyClass.php which obviously can't be found.

    Either use another means of prepending the directory, like a predetermined list, use the first part of the namespace (so just ditch the __DIR__) or move the classes to location relative to directory in which your include file resides.