奇怪的PHP循环范围我缺少什么?

时间:2020-05-12 08:08:22

标签: php loops

我在这里有3种不同类型的数组/对象

第一:

$myObj = [
    (object) [
        'fritz'   => 1,
        'michael' => 2,
        'hans'    => 3,
        'jurgen'  => 4,
    ]
];

foreach ( $myObj as $key => $val ) {
    $val->michael = 'lorem ipsum...';
}

print_r( $myObj );

输出:

Array
(
    [0] => stdClass Object
        (
            [fritz] => 1
            [michael] => lorem ipsum...
            [hans] => 3
            [jurgen] => 4
        )
)

第二:

$myArr = [
    [
        'fritz'   => 1,
        'michael' => 2,
        'hans'    => 3,
        'jurgen'  => 4,
    ]
];


foreach ( $myArr as $key => $val ) {
    $val['michael'] = 'lorem ipsum...';
}

print_r( $myArr );

输出:

Array
(
    [0] => Array
        (
            [fritz] => 1
            [michael] => 2
            [hans] => 3
            [jurgen] => 4
        )
)

为什么在第一个示例中$ myObj实际上已更改,但从未在循环内对其进行访问。据我所知,循环正在处理副本,并且永远不会更改原始副本。我想念什么? 循环期间数组和对象访问之间是否有区别?

0 个答案:

没有答案