一次包含子文件夹的php文件

时间:2018-11-20 12:20:50

标签: php

在PHP中,我有一个带有子文件夹的文件夹,该子文件夹包含带有类或接口的.php文件。在该级别以下,没有其他子文件夹。 某些类扩展了在其他文件夹中指定的其他类。

结构:

MAINFOLDER
- FOLDER1
-- Class1.php
-- Interface1.php
-- Class2.php
- FOLDER2
-- Class3.php
-- Class4.php
-- Interface2.php
- FOLDER3
-- Interface3.php
-- Class5.php

我尝试了以下代码:

$foldernames = ['FOLDER1','FOLDER2','FOLDER3'];
        foreach ($foldernames as $foldername) {
            foreach (glob('MAINFOLDER/'.$foldername.'/*.php') as $file) {
                include_once $file;
            }
        }

该代码无效。 任何人都有一个想法如何轻松地一次包含所有类和接口?

1 个答案:

答案 0 :(得分:1)

spl_autoload_register()是为此而设计的。

它将使用参数中给定的回调来自动包括缺少的类。

例如:

spl_autoload_register(function ($className)
{
    $foldernames = ['FOLDER1','FOLDER2','FOLDER3'];
    foreach ($foldernames as $foldername)
    {
        //This example requires, of course, a correct naming of class files
        $file = 'MAINFOLDER/' . $foldername . '/' . $className . '.php';
        if (file_exists($file))
            include $file;
    }
});