9

I am building a PHP application that uses a select menu to build email templates. The templates are broken into reusable parts (each is a separate html file). Is there an easy way to require multiple files with one expression? (my PHP is really rusty...)

Essentially I want to do something like:

function require_multi() {
    require_once($File1);
    require_once($File2);
    require_once($File3);
    require_once($File4);
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
MBguitarburst
  • 267
  • 1
  • 7
  • 21

3 Answers3

14

Well, you could turn it into a function:

function require_multi($files) {
    $files = func_get_args();
    foreach($files as $file)
        require_once($file);
}

Use like this:

require_multi("one.php", "two.php", ..);

However, if you're including classes, a better solution would be to use autoloading.

alexn
  • 57,867
  • 14
  • 111
  • 145
6

Credit to Tom Haigh from how to require all files in a folder?:

$files = glob( $dir . '/*.php' );
foreach ( $files as $file )
    require( $file );

Store all your required files in $dir and the above code will do the rest.

Community
  • 1
  • 1
Nahydrin
  • 13,197
  • 12
  • 59
  • 101
  • It COULD be very useful for debugging. I'm in a situation now where I need to load all the css files that are in `./css`, so it woks. (for debugging, not production) – Native Coder Jan 20 '17 at 15:24
  • This would only work as it stands if the files are in the correct order and there is no dependency on a later file for any of them. If you number the files, this would work fine. – ClarkeyBoy Sep 04 '21 at 20:02
2

EDIT:

Because you want to require or include multiple files, you could use this recursive algorithm to include files in a specified folder. The folder is the root that starts the iterator. Because the algorithm is recursive, it will automatically traverse all subsequent folders and include those files as well.

public function include_all_files($root) {
    $d = new RecursiveDirectoryIterator($root);
    foreach (new RecursiveIteratorIterator($d) as $file => $f) {
        $ext = pathinfo($f, PATHINFO_EXTENSION);
        if ($ext == 'php' || $ext == 'inc')
            include_once ($file); // or require(), require_once(), include_once()
    }
}

include_all_files('./lib');
JohnnyStarr
  • 619
  • 8
  • 21
  • This solution is only good if he wants to load classes. Thus, those utilities functions that he reuses may not be in classes. So, it's not a good answer I guess for it's problem. Still, it's an interesting one for loading classes automatically. – Patrick Desjardins Jan 23 '12 at 16:23
  • `$d = new RecursiveDirectoryIterator($fullPath, FilesystemIterator::SKIP_DOTS);` Use this for skipping dots – Md. A. Apu Jun 21 '20 at 08:39