以下代码有什么问题

时间:2013-11-06 05:40:19

标签: php

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

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路径

请询问是否有任何疑问

2 个答案:

答案 0 :(得分:0)

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

$file = $this->_findFile($current_path . "/", $class);
if ($file) {
     return $file;
}

答案 1 :(得分: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;
}