I have been experimenting with autoloader class directory mapping techniques, and it has been a bit of a struggle. I managed to come up with a fairly straightforward solution (on the surface), but I'm totally mystified that it works at all, while other, "more obvious" solutions failed. Below are some code snippets that illustrate my confusion.
Here's the working code:
<?php
spl_autoload_register('my_autoloader');
function my_autoloader($class) {
$classMap = array(
'classes/',
'classes/sites/',
'classes/data/'
);
foreach ($classMap as $location) {
if (!@include_once($location . $class . '.php')) { // @ SUPPRESSES include_once WARNINGS
// CLASS DOESN'T EXIST IN THIS DIRECTORY
continue;
} else {
// CLASS IS AUTO-LOADED
break;
}
}
}
?>
Here's a snippet that I felt should work, but doesn't:
<?php
spl_autoload_register('my_autoloader');
function my_autoloader($class) {
$classMap = array(
'classes/',
'classes/sites/',
'classes/data/'
);
foreach ($classMap as $location) {
if (file_exists($location . $class . '.php')) {
require_once ($location . $class . '.php');
}
}
}
?>
The latter makes more sense to me because while these two versions work:
<?php
spl_autoload_register('my_autoloader');
function my_autoloader($class) {
require_once ('classes/sites/' . $class . '.php');
}
?>
<?php
spl_autoload_register('my_autoloader');
function my_autoloader($class) {
$location = 'classes/sites/';
require_once ($location . $class . '.php');
}
?>
This one throws "No such file or directory..." (note the lack of "sites/" in the path.
<?php
spl_autoload_register('my_autoloader');
function my_autoloader($class) {
require_once ('classes/' . $class . '.php');
}
?>
The "No such file or directory..." error made me think I could simply check for a class's supporting file and, if (file_exists()) {require_once(); break;} else {continue;}
Why doesn't that work? And, why DOES the first snippet work? The supporting path/file is never explicitly included or required.