代码之家  ›  专栏  ›  技术社区  ›  Daniel Bingham

在PHP中包含整个目录还是在PHP中使用通配符Include?

  •  6
  • Daniel Bingham  · 技术社区  · 15 年前

    require_once('CommandA.php');
    require_once('CommandB.php');
    require_once('CommandC.php');
    
    class Interpreter {
        // Interprets input and calls the required commands.
    }
    

    有没有办法将所有这些命令都包含在一个单独的require\u中一次?在我的代码中的许多其他地方(工厂、建设者和其他解释器)都有类似的问题。这个目录中只有命令,解释器需要目录中的其他所有文件。是否有可以在require中使用的通配符?例如:

    require_once('*.php');
    
    class Interpreter { //etc }
    

    有没有其他方法不需要在文件顶部包含20行的include?

    5 回复  |  直到 15 年前
        1
  •  6
  •   Spartacus    7 年前

    你为什么要这么做?当需要库来提高速度和减少占用空间时,只包含库不是更好的解决方案吗?

    Class Interpreter 
    {
        public function __construct($command = null)
        {
            $file = 'Command'.$command.'.php';
    
            if (!file_exists($file)) {
                 throw new Exception('Invalid command passed to constructor');
            }
    
            include_once $file;
    
            // do other code here.
        }
    }
    
        2
  •  19
  •   deceze    15 年前
    foreach (glob("*.php") as $filename) {
        require_once $filename;
    }
    

    不过,我会小心处理这样的事情,而且总是喜欢“手动”包含文件。如果这太麻烦了,也许应该进行一些重构。另一个解决办法可能是 autoload classes

        3
  •  8
  •   Fanis Hatzidakis    15 年前

    您不能只需要一个通配符,但可以通过编程方式查找该目录中的所有文件,然后在循环中要求它们

    foreach (glob("*.php") as $filename) {
        require_once($filename) ;
    }
    

    http://php.net/glob

        4
  •  2
  •   Oyeme    15 年前

    可以使用foreach()包含所有文件

    $array =  array('read','test');
    
    foreach ($array as $value) {
        include_once $value.".php";
    }
    
        5
  •  1
  •   seanTcoyote    11 年前

    现在是2015年,所以您很可能正在运行PHP>=5。如果是这样的话,正如上面几次提到的,PHP的自动加载功能是一个很好的解决方案,可能是最好的。它是专门创建的,因此您不必编写自动加载的实用程序函数。但是,正如PHP文档中提到的, __autoload 不再推荐,在将来的版本中可能会贬值。只要您使用的是PHP>=5.1.2,就可以使用 spl_autoload_register 相反。