1

我有这个功能可以从任何级别的目录中查找类

function _findFile($path, $class) {
        $founded_file = "";
        $dir = scandir($path);
        foreach ($dir as $file) {
            $current_path = $path . $file;
//            echo $current_path . "\n";
            if ($file != "." && $file != "..") {
//                    echo $current_path . "\n";
                if (is_dir($current_path)) {
                    return $this->_findFile($current_path . "/", $class);
                } else if (is_file($current_path) && end(explode(".", $current_path)) === "php") {
                    if (end(explode("/", $current_path)) === ($class . ".php")) {
                        return $current_path;
                    }
                }
            }
        }

        return $founded_file;
    }

我的目录结构

system
  -base
     -core.php
     -exceptions.php
  -database
     -database.php

它不是在其中找到文件system > database

如果您取消注释第一个评论,那么您可以看到该函数没有进入system > database路径

请询问是否有任何疑问

4

2 回答 2

0

尝试更换$this->_findFile($current_path . "/", $class)

$file = $this->_findFile($current_path . "/", $class);
if ($file) {
     return $file;
}
于 2013-11-06T06:11:55.297 回答
0

您可能想知道RecursiveDirectoryIteratorFilterIterator类,它们将帮助您大大简化代码:

<?php

class FileFilterIterator extends FilterIterator 
{
    private $filename;

    public function __construct(Iterator $iterator, $filename)
    {
        parent::__construct($iterator);
        $this->filename = $filename;
    }

    public function accept()
    {
        return ($this->getInnerIterator()->current()->getFilename() == $this->filename);
    }
}

function _findFile($path, $className)
{
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
    $files = array();

    foreach (new FileFilterIterator($iterator, "$className.php") as $file) {
        $files[] = $file->getPathname();
    }

    return $files;
}
于 2013-11-06T06:18:28.560 回答