在PHP中,我可以包括一个脚本目录吗?

例如:

include('classes/Class1.php');
include('classes/Class2.php');

比如:

include('classes/*');

似乎找不到一个好方法来为一个特定的类包含大约10个子类的集合。


当前回答

如果你想包含一堆类,而不必一次定义每个类,你可以使用:

$directories = array(
            'system/',
            'system/db/',
            'system/common/'
);
foreach ($directories as $directory) {
    foreach(glob($directory . "*.php") as $class) {
        include_once $class;
    }
}

这样你就可以在包含这个类的php文件中定义这个类,而不是整个$thisclass = new thisclass();

至于它处理所有文件的效果如何?我不确定这可能会有轻微的速度下降。

其他回答

<?php
//Loading all php files into of functions/ folder 

$folder =   "./functions/"; 
$files = glob($folder."*.php"); // return array files

 foreach($files as $phpFile){   
     require_once("$phpFile"); 
}

我建议您使用readdir()函数,然后循环并包含文件(请参阅该页上的第一个示例)。

这是一个后期的回答,涉及到PHP > 7.2到PHP 8。

OP在标题中没有询问职业,但从他的措辞中我们可以看出他想要包括职业。(顺便说一句。此方法也适用于名称空间)。

使用require_once,你可以用一条毛巾杀死三只蚊子。

首先,如果文件不存在,您将在日志文件中以错误消息的形式得到有意义的重击。这在调试时非常有用。(include只会生成一个可能不那么详细的警告) 只包含包含类的文件 您可以避免加载一个类两次

spl_autoload_register( function ($class_name) {
    require_once  '/var/www/homepage/classes/' . $class_name . '.class.php';
} );

这将适用于类

new class_name;

或名称空间。如……

use homepage\classes\class_name;

如果你想包含所有在一个目录和它的子目录:

$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;
}

不要忘记,它将使用字母顺序来包括您的文件。

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文档推荐:自动加载类