包括PHP或Wildcard中的整个目录以用于PHP Include?

问题描述 投票:6回答:5

我在php中有一个命令解释器。它位于命令目录中,需要访问命令文件中的每个命令。目前我在每个命令上调用一次。

require_once('CommandA.php');
require_once('CommandB.php');
require_once('CommandC.php');

class Interpreter {
    // Interprets input and calls the required commands.
}

有没有一个包含所有这些命令与一个require_once?我的代码中有许多其他地方(包括工厂,建筑商和其他口译员)也有类似的问题。此目录中只有命令,解释器需要目录中的所有其他文件。是否有可以在require中使用的通配符?如:

require_once('*.php');

class Interpreter { //etc }

有没有其他方法可以在文件顶部包含20行包含?

php include wildcard require
5个回答
4
投票

你为什么要那样做?当需要它来提高速度和减少占用空间时,它不是一个更好的解决方案吗?

像这样的东西:

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.
    }
}

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

我会小心那样的东西,但总是喜欢“手动”包括文件。如果这太麻烦了,也许有些重构是有道理的。另一个解决方案可能是autoload classes


7
投票

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

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

http://php.net/glob


2
投票

您可以使用foreach()包含所有文件 将所有文件名存储在数组中。

$array =  array('read','test');

foreach ($array as $value) {
    include_once $value.".php";
}

0
投票

现在是2015年,所以你最有可能运行PHP> = 5.如果是这样,如上所述,PHP的自动加载功能是一个很好的解决方案,可能是最好的。它是专门创建的,因此您不必为自动加载编写实用程序功能。但是,如PHP文档中所述,__autoload不再推荐,可能会在将来的版本中折旧。只要您使用PHP> = 5.1.2,请使用spl_autoload_register

© www.soinside.com 2019 - 2024. All rights reserved.