看板 PHP 關於我們 聯絡資訊
一個簡單的程式碼如下: $arr = array(1,2,3,4); foreach($arr as &$value) ; var_dump($arr); 得到的結果: array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> &int(4) } 根據官方的說明: http://php.net/manual/en/control-structures.foreach.php Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset(). 之前我一直都沒注意到這個現象 直到最近出現一個奇怪的錯誤弄半天弄不出來 發現是最後一項的指標在經過一段時間之後被指向另外一個資料... 官方文件有些討論重現了這個問題: Mark Rose 15-Dec-2010 10:55 himitsu at fnse dot de 08-Aug-2010 12:59 是不是根本就不要使用foreach($a as &$v) $v= 來改變$a? 寧願使用foreach($a as $k=>$v) $a[$k]= 或者說有確保安全跟效能的解決方法? 我程式碼好多地方都用了&$..... -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 122.116.180.163
arrack:我是都用後者,沒出現過問題 04/04 19:09
UniFish:...你了解加了個﹠的用意嗎? 04/04 20:31
linhomeyeu:官方上面就有給warning了... 04/04 21:14
buganini:unset 04/04 22:34