function getContents()返回意外结果

时间:2014-10-02 08:48:52

标签: php

我写了一个名为getContents()的函数:

// Get contents of specific DIR.  Will recur through all directories.
function getContents($path, $skip_dir = FALSE, $skip_files = "", $dir_only = FALSE, $recurse = TRUE) 
{   if($skip_files == "") $skip_files = array();
    $getContentsTmp = array();
    foreach(scandir($path, 1) as $file) 
    {   
        if(($file != ".") && ($file != "..")) 
        {   if((is_file($path . "/" . $file)) && (!in_array(pathinfo($path . "/" . $file,PATHINFO_EXTENSION),$skip_files)) && (!$dir_only))  {
                array_push($getContentsTmp, $file);
            }
            if((is_dir($path . "/" . $file)) && (!$skip_dir)) {
                if($recurse) {
                    $getContentsTmp[$file] = getContents($path . "/" . $file, $skip_files, $dir_only, $recurse);
                } else {
                    array_push($getContentsTmp,$file); 
                    // or $getContentsTmp[$file] = "";
                }
            }
        }
    }
    ksort($getContentsTmp);
    return $getContentsTmp;
}

很长一段时间以来一直很好。但由于某种原因,我今天在另一个目录上使用它,并且它没有返回预期的结果。我已将其缩小到$dir_only变量。出于某种原因,即使我没有设置它也是如此。我不会在任何地方更改变量,所以我不知道为什么会这样。

对函数的调用是这样的:

$e = getContents("my_dir");

如果我在函数中回显结果,它会正确地看到所有文件和文件夹,但是当它从内部再次调用该函数时,(在if($recurse)之后),它通过$ dir_only但似乎被解释为真。我无法弄清楚原因。

1 个答案:

答案 0 :(得分:4)

查看您传入的参数数量:

getContents($path . "/" . $file, $skip_files, $dir_only, $recurse);
                      ^              ^            ^         ^
                      1              2            3         4

查看您的函数接受的数量:

getContents($path, $skip_dir = FALSE, $skip_files = "", $dir_only = FALSE, $recurse = TRUE) 
             ^           ^               ^                     ^                ^
             1           2               3                     4                5

因此,在这种情况下,您正在调用该函数并错过$skip_dir,因此$recurse的值将应用于参数$dir_only

相关问题