views:

28

answers:

2

I've got a recursive function defined as follows

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;
  }
}

and I'm calling it like so

$reversePathway = $this->_buildPathwayRecurse($category);

However $reversePathway ends up being null. Any idea why that is? I've stepped through my code using XDebug and as far as I can tell everything works as it should. When I get to the line

return $reversePathway

$reversePathway looks perfect. It's persisting through the function calls and gaining a new item each time. right before executing the return line it's got an array of a few items just like it should be, but by the time I get out to

$reversePathway = $this->_buildPathwayRecurse($category);

it seems to just dissapear!

+1  A: 

Your if block is missing a return statement.

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;
  }
}
Ruel
+1  A: 

The if() block tells it to either recurse or return a value.

The first iteration will obviously recurse, so it won't do the return, so all your hard work building the array will not be returned out of the initial iteration.

You probably want it to return either way, rather than having an else clause.

Spudley