PHP - 非递归var_dump?
当处理某些 PHP 对象时,可以执行 var_dump()
并且 PHP 将值打印到屏幕上,这些值会不断地打印,直到达到我认为的 PHP 内存限制。一个例子是转储简单的 HTML DOM 对象。我假设因为您能够遍历对象的子对象和父对象,所以执行 var_dump()
会给出无限的结果,因为它找到对象的父对象,然后递归地找到它的子对象,然后找到所有这些子对象的父母并找到那些孩子,等等等等。它会一直持续下去。
我的问题是,如何避免这种情况并防止 PHP 一次又一次地递归地转储相同的内容?使用简单 HTML DOM 解析器示例,如果我有一个没有子对象的 DOM 对象,并且我使用 var_dump()
它,我希望它只转储该对象,而不开始遍历 DOM 树以及抛弃父母、祖父母、其他孩子等。
When dealing with certain PHP objects, it's possible to do a var_dump()
and PHP prints values to the screen that go on and on and on until the PHP memory limit is reached I assume. An example of this is dumping a Simple HTML DOM object. I assume that because you are able to traverse children and parents of objects, that doing var_dump()
gives infinite results because it finds the parent of an object and then recursively finds it's children and then finds all those children's parents and finds those children, etc etc etc. It will just go on and on.
My question is, how can you avoid this and keep PHP from dumping recursively dumping out the same things over and over? Using the Simple HTML DOM parser example, if I have a DOM object that has no children and I var_dump()
it, I'd like it to just dump the object and no start traversing up the DOM tree and dumping parents, grandparents, other children, etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的开发环境中安装 XDebug 扩展。它将 var_dump 替换为自己的 var_dump,默认情况下仅深入 3 个成员。
https://xdebug.org/docs/display
它将显示 4 层深度的项目作为省略号。您可以使用 ini 设置更改深度。
所有 PHP 函数:var_dump、var_export 和 print_r 都不跟踪递归/循环引用。
编辑:
如果你想以困难的方式做到这一点,你可以编写自己的函数
Install XDebug extension in your development environment. It replaces var_dump with its own that only goes 3 members deep by default.
https://xdebug.org/docs/display
It will display items 4 levels deep as an ellipsis. You can change the depth with an ini setting.
All PHP functions: var_dump, var_export, and print_r do not track recursion / circular references.
Edit:
If you want to do it the hard way, you can write your own function
为什么不在对象上简单地运行
foreach
循环呢?来自 PHP 文档:
Why don't you simply run a
foreach
loop on your object?From the PHP docs:
我遇到了这个问题,不需要查看对象内部,只需查看对象类名,因此我编写了一个简单的函数,在转储数据之前用对象的类名替换对象:
然后,当您想转储某些内容时,只需执行以下操作:
I had this problem and didn't need to see inside the objects, just the object classnames, so I wrote a simple function to replace objects with their classnames before dumping the data:
Then, when you want to dump something, just do this: