PHP foreach by reference 在遍历对象数组时会导致奇怪的故障
我有一个对象数组.对象主要有一堆属性,因为这些是元数据对象.
I have an array of objects. The objects mainly have a bunch of properties because these are meta-data objects.
所以就像$objects[]
就像一堆具有以下属性的项目:object->item1
、object->item2
等
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);
}
然后,我想将这些对象显示为 html 中的列表.所以,我去:
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??
这对你有意义吗?
推荐答案
如果你通过引用迭代,之后总是取消设置迭代变量:
If you iterate by reference, always unset the iteration variable afterwards:
foreach ($objects as &$object) {
// some code
}
unset($object);
摘自 foreach
文档:
Excerpt from the foreach
documentation:
即使在 foreach 循环之后,对 $value 和最后一个数组元素的引用仍然存在.建议用unset()销毁.
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().
如果您想了解为什么您的代码的行为方式如此,这里有一些进一步的阅读:引用和foreach
If you want to understand why your code behaves the way it behaves, here is some further reading: References and foreach
相关文章