递归函数不返回PHP中的值

rus*_*nge 1 php recursion pass-by-reference

我有一个定义如下的递归函数

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

我这样称呼它

$reversePathway = $this->_buildPathwayRecurse($category);
Run Code Online (Sandbox Code Playgroud)

但是$ reversePathway最终为null.知道为什么会这样吗?我已经使用XDebug逐步完成了我的代码,据我所知,一切正常.当我到达线

return $reversePathway
Run Code Online (Sandbox Code Playgroud)

$ reversePathway看起来很完美.它持续通过函数调用并每次获得一个新项目.在执行返回线之前,它有一个像应该的一样的几个项目的数组,但到我出去的时候

$reversePathway = $this->_buildPathwayRecurse($category);
Run Code Online (Sandbox Code Playgroud)

它似乎只是消失了!

小智 6

你错过了一个return语句.尝试

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;
  }
}
Run Code Online (Sandbox Code Playgroud)