Require all files in a folder

后端 未结 9 1416
南旧
南旧 2020-12-28 13:13

Is there an easy way to programmatically require all files in a folder?

相关标签:
9条回答
  • Simple:

    foreach(glob("path/to/my/dir/*.php") as $file){
        require $file;
    }
    
    0 讨论(0)
  • 2020-12-28 13:33

    My way to require all siblings:

    <?php
    $files = glob(__DIR__ . '/*.php');
    foreach ($files as $file) {
        // prevents including file itself
        if ($file != __FILE__) {
            require($file);
        }
    }
    
    0 讨论(0)
  • 2020-12-28 13:36

    Solution using opendir, readdir, closedir. This also includes subdirectories.

    <?php
    function _require_all($path, $depth=0) {
        $dirhandle = @opendir($path);
        if ($dirhandle === false) return;
        while (($file = readdir($dirhandle)) !== false) {
            if ($file !== '.' && $file !== '..') {
                $fullfile = $path . '/' . $file;
                if (is_dir($fullfile)) {
                    _require_all($fullfile, $depth+1);
                } else if (strlen($fullfile)>4 && substr($fullfile,-4) == '.php') {
                    require $fullfile;
                }
            }
        }
    
        closedir($dirhandle);
    }        
    
    //Call like
    _require_all(__DIR__ . '/../vendor/vlucas/phpdotenv/src');
    
    0 讨论(0)
提交回复
热议问题