如何包含()目录中的所有PHP文件?

occ*_*iso 224 php include

非常快的n00b问题,在PHP中我可以包含一个脚本目录.

即代替:

include('classes/Class1.php');
include('classes/Class2.php');
Run Code Online (Sandbox Code Playgroud)

是这样的:

include('classes/*');
Run Code Online (Sandbox Code Playgroud)

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

Kar*_*ten 427

foreach (glob("classes/*.php") as $filename)
{
    include $filename;
}
Run Code Online (Sandbox Code Playgroud)

  • 当需要扩展基类的类时,此方法并不好:例如,如果BaseClass出现在数组AFTER ExtendedClass中,它就不会工作! (20认同)
  • 我会用配置文件构建一个合适的模块系统,但这只是因为我发现它比仅包括*所有*更灵活.:-) (5认同)
  • 我认为使用include()会有一个更干净的方式.但这样做会很好.感谢大家. (4认同)
  • 注意,仅适用于在当前目录中包含文件.可以通过get_include_path()进行迭代,但这很快就会变得乏味. (3认同)
  • @nalply`get_include_path()`仍然无法自动确定加载顺序(基类可能会加载AFTER扩展类,产生错误) (2认同)
  • 我会将glob更改为"glob(_ _DIR_ _."/ src/**/*.php")" (2认同)

Mar*_*ius 50

这是我在PHP 5中包含来自几个文件夹的许多类的方法.这只有在你有类的情况下才有效.

/*Directories that contain classes*/
$classesDir = array (
    ROOT_DIR.'classes/',
    ROOT_DIR.'firephp/',
    ROOT_DIR.'includes/'
);
function __autoload($class_name) {
    global $classesDir;
    foreach ($classesDir as $directory) {
        if (file_exists($directory . $class_name . '.php')) {
            require_once ($directory . $class_name . '.php');
            return;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 自动加载是不相关的,因为这个问题是关于将所有内容都包含在目录中 - 通常这将在不同的目录中:例如,在BE目录中定义的DataClass和在BL目录中定义的BL.class.php. (3认同)

Ban*_*ing 32

我意识到这是一个较旧的帖子但是......不要包括你的课程......而是使用__autoload

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

$user = new User();
Run Code Online (Sandbox Code Playgroud)

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


Sor*_*inV 20

如果您使用的是PHP 5,则可能需要使用自动加载.


小智 20

这只是对Karsten代码的修改

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

include_all_php("my_classes");
Run Code Online (Sandbox Code Playgroud)

  • 这不会添加任何与接受的答案相关的内容. (12认同)

Sor*_*n C 18

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
} );
Run Code Online (Sandbox Code Playgroud)

这里的PHP文档推荐:自动加载类

  • 这并没有回答问题,因为只有当有人尝试即创建尚未加载的类的对象时,`autoload` 才会起作用。 (2认同)

alb*_*anx 9

你可以使用set_include_path:

set_include_path('classes/');
Run Code Online (Sandbox Code Playgroud)

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

  • 它不会自动包含目录中的所有php文件,只允许在使用`include` /`require`时省略`classes /` (13认同)