在PHP中,我可以包括一个脚本目录吗?
例如:
include('classes/Class1.php');
include('classes/Class2.php');
比如:
include('classes/*');
似乎找不到一个好方法来为一个特定的类包含大约10个子类的集合。
在PHP中,我可以包括一个脚本目录吗?
例如:
include('classes/Class1.php');
include('classes/Class2.php');
比如:
include('classes/*');
似乎找不到一个好方法来为一个特定的类包含大约10个子类的集合。
当前回答
如果你想包含所有在一个目录和它的子目录:
$dir = "classes/";
$dh = opendir($dir);
$dir_list = array($dir);
while (false !== ($filename = readdir($dh))) {
if($filename!="."&&$filename!=".."&&is_dir($dir.$filename))
array_push($dir_list, $dir.$filename."/");
}
foreach ($dir_list as $dir) {
foreach (glob($dir."*.php") as $filename)
require_once $filename;
}
不要忘记,它将使用字母顺序来包括您的文件。
其他回答
你可以使用set_include_path:
set_include_path('classes/');
http://php.net/manual/en/function.set-include-path.php
2017年如何做到这一点:
spl_autoload_register( function ($class_name) {
$CLASSES_DIR = __DIR__ . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR; // or whatever your directory is
$file = $CLASSES_DIR . $class_name . '.php';
if( file_exists( $file ) ) include $file; // only include if file exists, otherwise we might enter some conflicts with other pieces of code which are also using the spl_autoload_register function
} );
这里由PHP文档推荐:自动加载类
如果文件之间没有依赖关系…下面是一个递归函数来包含所有子dirs中的include_once所有php文件:
$paths = array();
function include_recursive( $path, $debug=false){
foreach( glob( "$path/*") as $filename){
if( strpos( $filename, '.php') !== FALSE){
# php files:
include_once $filename;
if( $debug) echo "<!-- included: $filename -->\n";
} else { # dirs
$paths[] = $filename;
}
}
# Time to process the dirs:
for( $i=count($paths)-1; $i>0; $i--){
$path = $paths[$i];
unset( $paths[$i]);
include_recursive( $path);
}
}
include_recursive( "tree_to_include");
# or... to view debug in page source:
include_recursive( "tree_to_include", 'debug');
如果你想包含所有在一个目录和它的子目录:
$dir = "classes/";
$dh = opendir($dir);
$dir_list = array($dir);
while (false !== ($filename = readdir($dh))) {
if($filename!="."&&$filename!=".."&&is_dir($dir.$filename))
array_push($dir_list, $dir.$filename."/");
}
foreach ($dir_list as $dir) {
foreach (glob($dir."*.php") as $filename)
require_once $filename;
}
不要忘记,它将使用字母顺序来包括您的文件。
尝试使用库来实现这个目的。
这是我构建的相同想法的一个简单实现。 它包括指定的目录和子目录文件。
IncludeAll
通过终端[cmd]安装
composer install php_modules/include-all
或者将其设置为包中的依赖项。json文件
{
"require": {
"php_modules/include-all": "^1.0.5"
}
}
使用
$includeAll = requires ('include-all');
$includeAll->includeAll ('./path/to/directory');