Reputation: 509
In PHP I have a folder with subfolders that contain .php files with either classes or interfaces. There are no further subfolders below that level. Some classes extend other classes which are specified in other folders.
Structure:
MAINFOLDER
- FOLDER1
-- Class1.php
-- Interface1.php
-- Class2.php
- FOLDER2
-- Class3.php
-- Class4.php
-- Interface2.php
- FOLDER3
-- Interface3.php
-- Class5.php
I have tried this code:
$foldernames = ['FOLDER1','FOLDER2','FOLDER3'];
foreach ($foldernames as $foldername) {
foreach (glob('MAINFOLDER/'.$foldername.'/*.php') as $file) {
include_once $file;
}
}
The code doesn't work. Anyone has an idea how to easily include all classes and interfaces at once?
Upvotes: 1
Views: 63
Reputation: 15247
spl_autoload_register() is made for that.
It will use the callback given in parameter to include automatically a missing class.
In example :
spl_autoload_register(function ($className)
{
$foldernames = ['FOLDER1','FOLDER2','FOLDER3'];
foreach ($foldernames as $foldername)
{
//This example requires, of course, a correct naming of class files
$file = 'MAINFOLDER/' . $foldername . '/' . $className . '.php';
if (file_exists($file))
include $file;
}
});
Upvotes: 1