How can the efficiency of an autoloader be improved to ensure that files are loaded only when needed?
To improve the efficiency of an autoloader and ensure that files are loaded only when needed, we can implement a mechanism to check if the file has already been loaded before attempting to load it. This can be achieved by keeping track of the files that have been loaded in a static array and checking against this array before loading a file.
class Autoloader {
private static $loadedFiles = [];
public static function loadClass($className) {
if (!in_array($className, self::$loadedFiles)) {
$file = str_replace('\\', '/', $className) . '.php';
if (file_exists($file)) {
require $file;
self::$loadedFiles[] = $className;
}
}
}
}
spl_autoload_register('Autoloader::loadClass');