Is there an easy way to programmatically require all files in a folder?
foreach
Loop.foreach (glob("classes/*") as $filename) {
require $filename;
}
For more details, check out this previously posted question:
Probably only by doing something like this:
$files = glob($dir . '/*.php');
foreach ($files as $file) {
require($file);
}
It might be more efficient to use opendir()
and readdir()
than glob()
.
As require_all() function:
//require all php files from a folder
function require_all ($path) {
foreach (glob($path.'*.php') as $filename) require_once $filename;
}
recursively all file list and require_once in one directory:
$files = array();
function require_once_dir($dir){
global $files;
$item = glob($dir);
foreach ($item as $filename) {
if(is_dir($filename)) {
require_once_dir($filename.'/'. "*");
}elseif(is_file($filename)){
$files[] = $filename;
}
}
}
$recursive_path = "path/to/dir";
require_once_dir($recursive_path. "/*");
for($f = 0; $f < count($files); $f++){
$file = $files[$f];
require_once($file);
}
No short way of doing it, you'll need to implement it in PHP. Something like this should suffice:
foreach (scandir(dirname(__FILE__)) as $filename) {
$path = dirname(__FILE__) . '/' . $filename;
if (is_file($path)) {
require $path;
}
}
There is no easy way, as in Apache, where you can just Include /path/to/dir
, and all the files get included.
A possible way is to use the RecursiveDirectoryIterator from the SPL:
function includeDir($path) {
$dir = new RecursiveDirectoryIterator($path);
$iterator = new RecursiveIteratorIterator($dir);
foreach ($iterator as $file) {
$fname = $file->getFilename();
if (preg_match('%\.php$%', $fname)) {
include($file->getPathname());
}
}
}
This will pull all the .php
ending files from $path
, no matter how deep they are in the structure.