Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

autoloader

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.

like image 464
dqhendricks Avatar asked Sep 02 '25 13:09

dqhendricks


1 Answers

No. You could load a different file. You could load no file. You could load several files. But after autoloading, PHP expects the class to exist like it was called.

If you call a class X, you can't magically give PHP class Y.

Maybe it's enough to set up the filesystem like that, but still keep literal class names?

PS
I've wanted this for a while too. When I didn't have access to namespaces yet. Now that I do, all my problems are solved =) If you do have access to namespaces, you should 'study' PSR-0.

like image 98
Rudie Avatar answered Sep 05 '25 17:09

Rudie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!