我在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行包含吗?
答案 0 :(得分:18)
foreach (glob("*.php") as $filename) {
require_once $filename;
}
我会小心那样的东西,但总是喜欢“手动”包括文件。如果这太麻烦了,也许有些重构是有道理的。另一种解决方案可能是autoload classes。
答案 1 :(得分:7)
你不能require_once一个通配符,但是你可以通过编程方式找到该目录中的所有文件,然后在循环中要求它们
foreach (glob("*.php") as $filename) {
require_once($filename) ;
}
答案 2 :(得分: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.
}
}
答案 3 :(得分:2)
您可以使用foreach()包含所有文件
将所有文件名存储在数组中。
$array = array('read','test');
foreach ($array as $value) {
include_once $value.".php";
}
答案 4 :(得分:0)
现在是2015年,因此您最有可能运行PHP> = 5.如果是这样,如上所述,PHP的自动加载功能是一个很好的解决方案,可能最好的。它是专门创建的,因此您不必为自动加载编写实用程序功能。但是,如PHP文档中所述,不再推荐使用__autoload,并且可能会在将来的版本中对其进行折旧。只要您使用PHP> = 5.1.2,请改用spl_autoload_register。