Search code examples
phpautoloader

Is there a way to dynamically change the name of the class being autoloaded?


For instance, say I have the following code.

$foo = new bar();

And an autoloader like this.

function autoload($class_name) {
    $class_file_name = str_replace('_', '/', $class_name) . '.php';
    if (file_exists($class_file_name)) {
        include($class_file_name);
    }
}

But the class I really want to load is in the folder 'foo/bar.php', and the real class name is actually foo_bar. Is there a way to dynamically change the name of the class being autoloaded? For instance, something like this?

function autoload(&$class_name) {
    $class_name = 'foo_' . $class_name;
    $class_file_name = str_replace('_', '/', $class_name) . '.php';
    if (file_exists($class_file_name)) {
        include($class_file_name);
    }
}

I know if something like this is possible, it is not exactly best practice, but I would still like to know if it is.


Solution

  • Maybe you can use class_alias, this way:

    • PHP requires class X
    • You want load class Y instead.
    • You create an alias X for class Y, so X will behave like Y.

    E.g.:

    function autoload($class_name) {
        $real_class_name = 'foo_' . $class_name;
        $class_file_name = str_replace('_', '/', $real_class_name) . '.php';
        if (file_exists($class_file_name)) {
            include($class_file_name);
            class_alias($real_class_name, $class_name);
        }
    }
    

    Hope it can help you.