php:stdclass数组元素在通过指针引用元素后更改

时间:2014-04-19 14:14:16

标签: php arrays stdclass

人。当通过指针引用标准类数组元素时,我偶然发现了奇怪的情况。这个例子在php 5.4.3,windows XP,Apache

上运行
$myLittleArray = array();
$myLittleArray[0] = new stdClass;
$myLittleArray[0]->fruit = 'apple';

$myLittleArray[1] = new stdClass;
$myLittleArray[1]->fruit = 'banana';

$myLittleArray[2] = new stdClass;
$mla = &$myLittleArray[2];
$mla->fruit = 'kiwi';

print_r($myLittleArray);   // $myLittleArray[2]->fruit  displays as "kiwi"

foreach ($myLittleArray as $mla){
   $mla->pricePerPound = 0.0;
}

print_r($myLittleArray);   // $myLittleArray[2]->fruit  displays as "banana" ???

第一个printr语句显示

Array
(
[0] => stdClass Object
    (
        [fruit] => apple
    )

[1] => stdClass Object
    (
        [fruit] => banana
    )

[2] => stdClass Object
    (
        [fruit] => kiwi
    )
}

第二个printr语句(请注意$ myLittleArray [2] - >水果已更改为" banana"

Array
(
[0] => stdClass Object
    (
        [fruit] => apple
        [pricePerPound] => 0
    )

[1] => stdClass Object
    (
        [fruit] => banana
        [pricePerPound] => 0
    )

[2] => stdClass Object
    (
        [fruit] => banana
        [pricePerPound] => 0
    )
)

*/

如果我在最后一个foreach中使用不同的变量名,比如$ mla1,则代码按预期工作($myLittleArray[2]->fruit == 'kiwi')。这是一个php问题,还是我没有正确看待这个?

1 个答案:

答案 0 :(得分:2)

这是因为您之前已$mla提及$myLittleArray[2]。当foreach每次通过循环分配给$mla时,它实际上分配给$myLittleArray[2]。因此,第一次通过循环将$myLittleArray[2]设置为$myLittleArray[0]的副本,第二次将$myLittleArray[2]设置为$myLittleArray[1]的副本。