PHP对象父/子递归 [英] PHP object parent/child recursion

查看:66
本文介绍了PHP对象父/子递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有父子面向对象的关系.父对象有许多子对象,每个子对象都通过引用知道它的父对象.

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).

当我对根对象执行 var_dump() 时,它多次显示 ["parent"]=>RECURSION 并且生成的描述会很长.

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".

感谢您的帮助!

推荐答案

你没有做错任何事;你有一个父级引用它的子级,每个子级都有一个返回到它的父级的引用.当您 var_dump() 根对象时,它会遍历子对象以打印它们,并且由于每个子对象都有对父对象的引用,因此它会返回.因为这通常会导致无限循环(父 -> 子 -> 父 -> 子 -> ...),PHP 保留一个它已经访问过的对象列表,当它遇到一个时,它不会尝试转储再次打印,而是打印RECURSION".

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".

唯一需要注意的是 PHP 使用引用计数来进行垃圾收集,并且像这样的循环结构不会自行解决.结果,您的脚本将泄漏内存,这可能是也可能不是问题.要解决这个问题,您需要手动清理:就在父对象超出范围之前,您需要将所有父指针设置为空.

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.

另见:http://bugs.php.net/bug.php?id=33595

这篇关于PHP对象父/子递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆