Php 为什么临时变量需要在更改数组元素时使用,为什么需要在最后取消设置?
考虑下面的代码段,它通过引用传递数组的值,直接更改数组的值(将值转换为大写)Php 为什么临时变量需要在更改数组元素时使用,为什么需要在最后取消设置?,php,arrays,foreach,reference,unset,Php,Arrays,Foreach,Reference,Unset,考虑下面的代码段,它通过引用传递数组的值,直接更改数组的值(将值转换为大写) <?php $colors = array('red', 'blue', 'green', 'yellow'); foreach ($colors as &$color) { $color = strtoupper($color); } unset($color); /* ensure that following writes to $color will not modi
<?php
$colors = array('red', 'blue', 'green', 'yellow');
foreach ($colors as &$color) {
$color = strtoupper($color);
}
unset($color); /* ensure that following writes to
$color will not modify the last array element */
print_r($colors);
?>
我根本不理解上面的代码。我对上面的代码有以下几点疑问:
foreach
循环内部。为什么使用临时变量$color
,为什么在函数strtoupper()
中不传递引用&$color
,而只传递$color
$color
未设置?那里面装的是什么foreach
循环的代码中发生了什么。
请有人回答我的疑问
注意:上面的代码示例取自PHP手册的数组章节。这是防御性编程 在
foreach()
循环的每次迭代中,在$color
变量中创建对当前项值的引用,从而允许向其写入新值。但是迭代结束后,$color
变量仍然包含对最后一个数组项的值的引用,允许程序员重用$color
变量进行写入以更新数组中的该项,这可能不是预期的结果unset()
以您的示例为基础:
<?php
$colors = array('red', 'blue', 'green', 'yellow');
foreach ($colors as &$color) {
$color = strtoupper($color);
}
//unset($color);
/* ensure that following writes to
$color will not modify the last array element */
print_r($colors);
$color='hello';
print_r($colors);
删除/注释
unset
调用,在末尾(当然是在print\r
调用之前)向$color
变量添加一个write,您很快就会得到它。关键是在这里注释/删除unset(),看看真正的神奇发生了什么。接下来是答案。作为旁注,为了实现这一点,您可以使用array\u map:$colors=array\u map(“strtoupper”,$colors);
<?php
$colors = array('red', 'blue', 'green', 'yellow');
foreach ($colors as &$color) {
$color = strtoupper($color);
}
//unset($color);
/* ensure that following writes to
$color will not modify the last array element */
print_r($colors);
$color='hello';
print_r($colors);
Array
(
[0] => RED
[1] => BLUE
[2] => GREEN
[3] => YELLOW
)
Array
(
[0] => RED
[1] => BLUE
[2] => GREEN
[3] => hello
)