在 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.
}
}
相关文章