php的循环与引用的一个坑,php循环引用
上代码
<span>$arr</span> = <span>array</span><span>( </span>'a'=> 'a11', 'b'=> 'b22', 'c'=> 'c33',<span> ); </span><span>foreach</span> (<span>$arr</span> <span>as</span> <span>$k</span>=>&<span>$v</span><span>){ </span><span>//</span><span> Do somethind</span> <span>} </span><span>foreach</span> (<span>$arr</span> <span>as</span> <span>$k</span>=><span>$v</span><span>){ </span><span>var_dump</span>(<span>$v</span><span>); }</span>
这样的代码, var_dump 会输出什么? 各位可以试试, 答案
<span>string</span>(3) "a11" <span>string</span>(3) "b22" <span>string</span>(3) "b22"
结果里, 第三行变成了 key='b' 的value. 问题就出在第一个循环的引用.
今天就踩到了一个这样的坑, 查问题用了很久. 简单来说, foreach循环使用的引用, 循环结束后有所保留. php.net 着重写了:
Warning
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().
对于上面这个例子, 第一个循环结束后, $v引用仍然存在. 由于两个循环的变量命名一致, 第二个循环开始, $v 每次都会被赋值. 直到最后, $v 被设置成了
前一个元素的值.
原理很简单, 文档写的明明白白. 但如果工作中遇到相关的bug是很坑的, 定位需要很久. 还得需要写码的时候就注意:
1. 减少引用的使用
2. 如果需要在foreah使用引用, 应该用函数将封装起来

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
