PHP foreach by reference causes weird glitch when going through array of objects(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
这篇关于PHP foreach by reference 在遍历对象数组时会导致奇怪的故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP foreach by reference 在遍历对象数组时会导致奇怪的故障


- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01