Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP object parent/child recursion

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!

like image 301
Damien Avatar asked Jan 07 '11 15:01

Damien


1 Answers

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

like image 130
tdammers Avatar answered Oct 02 '22 09:10

tdammers