FlyingCat
FlyingCat

Reputation: 14250

How to use __autoload for different folders?

I am trying to autoload classes that are in different folders. Is that possible?

       function __autoload($class){
            require $class.'.php';
            require 'libs/'.$class.'.php';
            //this won't work.
        }

I want to autoload classes that are either in libs folder or on the root. Any thoughts? Thanks a lot.

Upvotes: 2

Views: 128

Answers (1)

lonesomeday
lonesomeday

Reputation: 237845

First, I suggest you look into spl_autoload_register, which is superior for doing this.

Second, you should use is_file to test whether the file exists, then try to load it. If you require a file that doesn't exist, your script will halt.

spl_autoload_register(function($class) {
    if (is_file($class . '.php')) {
        require $class . '.php';
    } elseif (is_file('libs/' . $class . '.php')) {
        require 'libs/' . $class . '.php';
    }
});

If you have multiple folders where the file could be, you could do something like this:

spl_autoload_register(function($class) {
    $folders = array ('.', 'libs', 'somewhere');

    foreach ($folders as $folder) {
        if (is_file($folder . '/' . $class . '.php')) {
            require $folder . '/' . $class . '.php';
        }
        if (class_exists($class)) break;
    }
});

Upvotes: 3

Related Questions