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)
我会小心那样的东西,但总是喜欢"手动"包括文件.如果这太麻烦了,也许有些重构是有道理的.另一种解决方案可能是自动加载类.
您不能require_once通配符,但您可以以编程方式查找该目录中的所有文件,然后在循环中要求它们
foreach (glob("*.php") as $filename) {
require_once($filename) ;
}
Run Code Online (Sandbox Code Playgroud)
你为什么要这么做?仅在需要增加速度并减少占用空间时才包含库,这不是更好的解决方案吗?
像这样:
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)
| 归档时间: |
|
| 查看次数: |
11040 次 |
| 最近记录: |