Mark Baker Mark Baker - 2 months ago 26
PHP Question

Fatal error: Nesting level too deep - recursive dependency?

I have a complex hierarchy of nested objects, with all of the child objects (stored an array of objects in the parent class) containing a property linking back to their parent: fairly simple and straightforward, with no real problems. If I do a var_dump of any object in the hierarchy, I'll get a recursive reference in the dump, exactly as I'd expect.

FIRSTGEN
_children array of objects of type SECONDGEN
SECONDGEN #1
_parent object of type FIRSTGEN
_children array of objects of type THIRDGEN
THIRDGEN #1
_parent object of type SECONDGEN
THIRDGEN #2
_parent object of type SECONDGEN
SECONDGEN #2
_parent object of type FIRSTGEN
_children array of objects of type THIRDGEN
THIRDGEN #3
_parent object of type SECONDGEN


I've recently added some new elements to that hierarchy, and they don't follow quite the same pattern. They are stored in an array of objects in the top-level parent, but contain a property linking them back, not to their parent, but to a sibling. When I do a var_dump now, I get a "Fatal error: Nesting level too deep - recursive dependency?".

FIRSTGEN
_children_1 array of objects of type SECONDGEN_1
SECONDGEN_1 #1
_parent object of type FIRSTGEN
_children array of objects of type THIRDGEN
THIRDGEN #1
_parent object of type SECONDGEN_1
THIRDGEN #2
_parent object of type SECONDGEN_1
SECONDGEN_1 #2
_parent object of type FIRSTGEN
_children array of objects of type THIRDGEN
THIRDGEN #3
_parent object of type SECONDGEN_1
_children_2 array of objects of type SECONDGEN_2
SECONDGEN_2 #1
_parent object of type SECONDGEN_1


Everything else within the code works correctly, with the exception of that var_dump(). I've tried creating a simpler example to demonstrate the problem, so that I could provide an example when asking this question; but haven't been able to replicate it in a short test, only within my more complex code.

I know that the solution is to refactor the relationship so that my _children_2 array of SECONDGEN_2 objects is held in the appropriate SECONDGEN_1 parent, making the parent relationship "correct"... I've already started doing this.
However, I'm intrigued by the error, and wondered if anybody else had encountered it (and how you dealt with it yourself).

Answer

Looks like a PHP limitation in self-referencing code and trying to display it with print_r, var_dump, var_export, or search through it with in_array. Basically there's no way for those functions to know where to stop recursing if an object is referenced cirularly.

According to this bug report the easiest way to reproduce this is:

$outText = var_export( $GLOBALS, true );
print_r($outText) ;

Other bug reports mention it too, with some more test cases. I'd say that if this is only triggered in var_dump you shouldn't worry too much about it. I definitely second Wrikken's suggestion about xdebug if this is for debugging purposes.

Comments