我有一个定义如下的递归函数
private function _buildPathwayRecurse(&$category, &$reversePathway = array()) {
$category->uri = FlexicontentHelperRoute::getCategoryRoute($category->id);
$reversePathway[] = $category;
if ($category->parent_id != 0) {
$category = $this->_getCatForPathway($category->parent_id);
$this->_buildPathwayRecurse($category, $reversePathway);
} else {
return $reversePathway;
}
}
我正在这样称呼它
$reversePathway = $this->_buildPathwayRecurse($category);
然而$ reversePathway最终为null。知道为什么会这样吗?我已经使用XDebug逐步完成了我的代码,据我所知,一切正常。当我到达行
return $reversePathway
$ reversePathway看起来很完美。它持续通过函数调用并每次获得一个新项目。在执行返回线之前,它有一个像应该的一样的几个项目的数组,但到我出去的时候
$reversePathway = $this->_buildPathwayRecurse($category);
它似乎只是消失了!
答案 0 :(得分:6)
您缺少一份退货声明。 尝试
private function _buildPathwayRecurse(&$category, &$reversePathway = array()) {
$category->uri = FlexicontentHelperRoute::getCategoryRoute($category->id);
$reversePathway[] = $category;
if ($category->parent_id != 0) {
$category = $this->_getCatForPathway($category->parent_id);
return $this->_buildPathwayRecurse($category, $reversePathway); //no assignment, the function will be executed but even if the inner part goes to the else block, there's nothing to hold the returned value.
//nothing to return when it gets here.
} else {
return $reversePathway;
}
}
答案 1 :(得分:4)
if()块告诉它递归或返回一个值。
第一次迭代显然会递归,因此它不会返回,所以构建数组的所有辛苦工作都不会从初始迭代中返回。
您可能希望它以任一方式返回,而不是使用else
子句。
答案 2 :(得分:3)
您的if
块缺少返回语句。
private function _buildPathwayRecurse(&$category, &$reversePathway = array()) {
$category->uri = FlexicontentHelperRoute::getCategoryRoute($category->id);
$reversePathway[] = $category;
if ($category->parent_id != 0) {
$category = $this->_getCatForPathway($category->parent_id);
$this->_buildPathwayRecurse($category, $reversePathway); //no assignment, the function will be executed but even if the inner part goes to the else block, there's nothing to hold the returned value.
//nothing to return when it gets here.
} else {
return $reversePathway;
}
}