Require all files in a folder

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

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

相关标签:
9条回答
  • 2020-12-28 13:18

    Use a foreach Loop.

    foreach (glob("classes/*") as $filename) {
      require $filename;
    }
    

    For more details, check out this previously posted question:

    0 讨论(0)
  • 2020-12-28 13:23

    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().

    0 讨论(0)
  • 2020-12-28 13:24

    As require_all() function:

    //require all php files from a folder
    function require_all ($path) {
    
        foreach (glob($path.'*.php') as $filename) require_once $filename;
    
    }
    
    0 讨论(0)
  • 2020-12-28 13:25

    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);
    }
    
    0 讨论(0)
  • 2020-12-28 13:30

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-28 13:32

    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.

    0 讨论(0)
提交回复
热议问题