【发布时间】:2015-04-13 19:14:23
【问题描述】:
我有这段 PHP 代码,但之前只写过一个递归函数。我想从一个特定的子目录开始并检查文件是否存在。如果它在目录中不存在,我想检查文件的父文件夹,然后递归地继续,直到我找不到文件并返回“”或找到文件并返回其内容。这是我的功能:
/**
* Recursive function to get sidebar from path and look up tree until we either
* find it or return blank.
*/
class MyClass{
public function findSidebarFromPath($path){
if(file_exists($_SERVER["DOCUMENT_ROOT"].implode("/", $path)."/sidebar.html")){
return file_get_contents($_SERVER["DOCUMENT_ROOT"].implode("/", $path)."/sidebar.html");
} else {
if(count($path) > 0){
# pop element off end of array.
$discard = array_pop($path);
$this->findSidebarFromPath($path);
} else {
return "";
}
}
}
}
所以当我调用它时,我会这样做:
$myclass = new MyClass();
$myclass->findSidebarFromPath(array("segment1", "segment2", "segment3"));
假设我要查找的文件位于名为“segment2”的目录中。该函数永远找不到它。 array_pop 函数不会弹出数组末尾的元素,然后调用 findSidebarFromPath 函数。
【问题讨论】:
-
这不是递归代码,因为您不会在任何地方调用
findSidebarFromPath()。您只需致电getSidebar(),您根本没有显示。 -
内部if分支不返回。
-
我重命名了发帖功能。对于那个很抱歉。现在应该更有意义了...$this->findSidebarFromPath($path);是我的意思。
-
哎呀。我只是回答了我自己的问题。现在它起作用了。现在我为提出这个问题感到羞耻:(
-
@BryanC 每个人都会犯错,不要不好意思问问题。另外,你学会了如何以不同的方式解决同样的问题。这总是一个优点。