2014-10-02 106 views
1

我寫了一個函數調用getContents():功能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,但似乎被解釋爲true。我無法弄清楚爲什麼。

回答

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

+1

非常感謝。我會從來沒有見過這樣的:) – Chud37 2014-10-02 09:04:48