Require multiple files

不羁的心 提交于 2019-11-29 19:16:59

问题


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);
}

回答1:


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.




回答2:


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.




回答3:


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');


来源:https://stackoverflow.com/questions/6638060/require-multiple-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!