PHP通过引用foreach会导致奇怪的小故障时,通过对象的数组 [英] PHP foreach by reference causes weird glitch when going through array of objects

查看:117
本文介绍了PHP通过引用foreach会导致奇怪的小故障时,通过对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象的数组。这些对象主要有一堆
属性,因为它们是元数据对象。



所以它就像
$对象[] 就像是一堆有如下属性的项目:
object-> item1 对象> item2 等等。

我想为每个对象添加一些东西,所以...

  foreach($ objects as& $ object){
$ object-> newItem =(something I compute);
}

然后,我想在html中显示这些对象作为列表。所以,我去:

  foreach($ objects as $ object){
< li><?php object output stuff here?>< / li>
}

好的。现在,它工作正常,除了最后一个对象被丢弃,
倒数第二个对象显示两次。 WTF ??



这对你有意义么? 如果你通过引用迭代,总是取消设置迭代变量:

$ $ $ $ $ $ $ $ foreach($ objects as& $ object){
//一些代码
}
unset($ object);

摘自 foreach 文档

lockquote
引用$ value和最后一个数组元素甚至在foreach循环之后仍然存在。建议使用unset()来销毁它。


如果您想了解代码的行为方式,请点击这里进一步阅读:参考和foreach


I have an array of objects. The objects mainly have a bunch of properties because these are meta-data objects.

so it is like $objects[] is like a bunch of items that have properties like: object->item1, object->item2, etc.

I want to add something to each of these objects, so...

foreach ($objects as &$object) {
  $object->newItem=(something I compute);
}

then later, I want to display these objects as a list in html. So, I go:

foreach ($objects as $object) {
  <li><?php object output stuff here ?></li>
}

ok. Now, it works fine, except the last object is discarded and the second to last object is displayed twice. WTF??

Does this make sense to you?

解决方案

If you iterate by reference, always unset the iteration variable afterwards:

foreach ($objects as &$object) {
      // some code
}
unset($object);

Excerpt from the foreach documentation:

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

If you want to understand why your code behaves the way it behaves, here is some further reading: References and foreach

这篇关于PHP通过引用foreach会导致奇怪的小故障时,通过对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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