沃梦达 / 编程问答 / php问题 / 正文

在 PHP 或通配符中包含整个目录以供 PHP 包含?

Including a whole directory in PHP or Wildcard for use in PHP Include?(在 PHP 或通配符中包含整个目录以供 PHP 包含?)

本文介绍了在 PHP 或通配符中包含整个目录以供 PHP 包含?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a command interpreter in php. It lives inside the commands directory and needs access to every command in the command file. Currently I call require once on each command.

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

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

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

Is there someway to include all of these commands with a single require_once? I have a similar problem many other places in my code (with factories, builders, other interpreters). There is nothing but commands in this directory and the interpreter needs every other file in the directory. Is there a wildcard that can be used in require? Such as:

require_once('*.php');

class Interpreter { //etc }

是否有任何其他方法不涉及文件顶部的二十行包含?

Is there any other way around this that doesn't involve twenty lines of include at the top of the file?

推荐答案

你为什么要这么做?仅在需要它以提高速度和减少占用空间时才包含该库不是更好的解决方案吗?

Why do you want to do that? Isn't it a better solution to only include the library when needing it to increase speed and reduce footprint?

类似这样的:

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

这篇关于在 PHP 或通配符中包含整个目录以供 PHP 包含?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 PHP 或通配符中包含整个目录以供 PHP 包含?

基础教程推荐