I've got a parent-child OO relationship. Parent obejcts has many child objects and every child object knows about it's parent by reference.
The parent can be a child too (basically its a tree).
When i do a var_dump() on the root object it says ["parent"]=>RECURSION many times and the generated description will be really long.
I'm wondering if i do something wrong. If yes, i'm interested in the "best practice".
Thanks for the help!
You're not doing anything wrong; you have a parent that has a reference to its children, and each child has a reference back to its parent. When you var_dump()
the root object, it iterates over the children to print them, and since each child has a reference to the parent, it walks back up. Because this would normally cause an infinite loop (parent -> child -> parent -> child -> ...), PHP keeps a list of object it has visited already, and when it encounters one, it doesn't try to dump it again but instead prints "RECURSION".
The only thing to look out for with this is that PHP uses reference counting for its garbage collection, and circular constructs like these don't resolve by themselves. As a result, your script will leak memory, which may or may not be a problem. To resolve this, you need to clean up manually: just before the parent object goes out of scope, you need to set all parent pointers to null.
See also: http://bugs.php.net/bug.php?id=33595
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With