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

例如:

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

比如:

include('classes/*');

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


当前回答

这只是卡斯顿代码的修改

function include_all_php($folder){
    foreach (glob("{$folder}/*.php") as $filename)
    {
        include $filename;
    }
}

include_all_php("my_classes");

其他回答

我知道这是一个老帖子,但是…不要包括你的课程……而是使用__autoload

function __autoload($class_name) {
    require_once('classes/'.$class_name.'.class.php');
}

$user = new User();

然后,每当你调用一个尚未包含的新类时,php将自动触发__autoload并为你包含它

不要编写函数()在目录中包含文件。你可能会失去变量作用域,可能不得不使用“global”。只需循环文件。

另外,当一个包含的文件的类名将扩展到另一个文件中定义的另一个类时,您可能会遇到困难——这个文件还没有包含。所以,要小心。

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

你可以使用set_include_path:

set_include_path('classes/');

http://php.net/manual/en/function.set-include-path.php

这只是卡斯顿代码的修改

function include_all_php($folder){
    foreach (glob("{$folder}/*.php") as $filename)
    {
        include $filename;
    }
}

include_all_php("my_classes");