Home > php教程 > php手册 > body text

php的循环与引用的一个坑,php循环引用

WBOY
Release: 2016-06-13 08:46:39
Original
1110 people have browsed it

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>
Copy after login

这样的代码, var_dump 会输出什么? 各位可以试试, 答案

<span>string</span>(3) "a11"
<span>string</span>(3) "b22"
<span>string</span>(3) "b22"
Copy after login

结果里, 第三行变成了 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使用引用,  应该用函数将封装起来

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template