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

Dan*_*ham 6 php wildcard require include

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

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

class Interpreter {
    // Interprets input and calls the required commands.
}
Run Code Online (Sandbox Code Playgroud)

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

require_once('*.php');

class Interpreter { //etc }
Run Code Online (Sandbox Code Playgroud)

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

dec*_*eze 18

foreach (glob("*.php") as $filename) {
    require_once $filename;
}
Run Code Online (Sandbox Code Playgroud)

我会小心那样的东西,但总是喜欢"手动"包括文件.如果这太麻烦了,也许有些重构是有道理的.另一种解决方案可能是自动加载类.

  • 如果某人能够将.php文件放在其中一个包含目录中,可能会通过利用某个地方的其他漏洞来解决安全漏洞.它还使得跟踪包含在哪里的内容变得更加困难. (5认同)

Fan*_*nis 7

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

foreach (glob("*.php") as $filename) {
    require_once($filename) ;
}
Run Code Online (Sandbox Code Playgroud)

http://php.net/glob


tho*_*alt 5

你为什么要这么做?仅在需要增加速度并减少占用空间时才包含库,这不是更好的解决方案吗?

像这样:

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.
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然[autoload](http://de.php.net/manual/en/function.spl-autoload-register.php)解决方案会更优雅一些。 (8认同)