您的位置:首页 > Web前端

Hidden Danger of References inside a Foreach Construct

2013-04-12 22:11 169 查看
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

That's a fact we've known for years. But I don't use it very often for it never works for me. My code is simplified as follows.

<?php

//This is the file content
$file = '<?php exit;?>
::1	1365393847	/healthcom/memcp.do	{"idnum":"450521199309333489","password":"123459"}	{"action":"login"}
::1	1365393858	/healthcom/register.do	{"info":"thisis a test"}	[]
::1	1365393869	/healthcom/memcp.do	{"idnum":"450521199309333489","password":"123459"}	{"action":"login"}';

//We read it and explode it into an array
$logs = explode("\r\n", $file);
unset($logs[0]);

//Handle each line
foreach($logs as &$log){
if(empty($log)){
continue;
}

$log = explode("\t", $log);
$log[1] = date($log[1]);
}

//Output the content directly. (Maybe you'd rather output the HTML in another file with a template engine.)
foreach($logs as $log){
print_r($log);
}

?>

There seems no problems. Unfortunately I got the output like this:

Array
(
[0] => ::1
[1] => 1365393847
[2] => /healthcom/memcp.do
[3] => {"idnum":"450521199309333489","password":"123459"}
[4] => {"action":"login"}
)
Array
(
[0] => ::1
[1] => 1365393858
[2] => /healthcom/register.do
[3] => {"info":"thisis a test"}
[4] => []
)
Array
(
[0] => ::1
[1] => 1365393858
[2] => /healthcom/register.do
[3] => {"info":"thisis a test"}
[4] => []
)

The last record was unexpectedly modified. I've been trying to find out what the problem it is.

There's a warning in the PHP manual.

Reference of a $value and the last array element remain even after theforeach loop. It is recommended to destroy it by
unset().

In the foreach construct, we've seen the $log is assigned a new value for each line. But the previous $log won't be affected because PHP seems to unset the reference on each loop ends and then start the next loop. But what on hell happened?
Why the final log was modified in the second foreach construct?

I tried to output the $logs with print_r($logs); instead of a foreach. It wasn't modified.

It's noticed that reference $log wasn't destroyed in the last loop of the first statement. So when the second one starts, $log (references to $logs[3]) was assigned a new value, $logs[1].

In conclusion, although $log won't be affected in each loop, $log will be still there until you unset it. And as an easily overlooked assignment statement, the foreach construct can be a hidden danger. Just unset every reference when it becomes unnecessary.

<?php

foreach($logs as &$log){
//Handle your $log
}
unset($log); //Don't miss me after each foreach construct with a reference. I'm in the PHP manual, but easily overlooked.

?>


Ha, now it works as expected~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐