简体   繁体   English

PHP使用递归数组的奇怪行为

[英]PHP Strange behaviour with recursive arrays

$array = array();
$array[ 'recursive' ] =& $array;

$array[ 'foo' ] = $array;

'foo' was assigned by value to $array , which should copy $array , which did not have a 'foo' key at the time, so I expect the situation to now be something like: 'foo'是按值分配给$array ,它应该复制$array ,当时没有'foo'键,所以我希望现在的情况如下:

$array = array(
    'recursive' => &$array,
    'foo'       => array(
        'recursive' => &$array
    ),
)

But if I now do: 但如果我现在这样做:

var_dump( isset( $array[ 'foo' ][ 'foo' ][ 'foo' ] ) );

I get: 我明白了:

bool(true)

I don't understand why this is. 我不明白为什么会这样。

If I create an intermediate variable for the assignment of 'foo' , like this: 如果我为'foo'的赋值创建一个中间变量,如下所示:

$array = array();
$array[ 'recursive' ] =& $array;

$blah = $array;
$array[ 'foo' ] = $blah;

var_dump( isset( $array[ 'foo' ][ 'foo' ][ 'foo' ] ) );

I get: 我明白了:

bool(false)

I understand why the 'recursive' key would be infinitely deep, because that was assigned by reference, but why the 'foo' key, which was assigned by value? 我理解为什么'recursive'键会无限深,因为它是通过引用分配的,但为什么'foo'键是由值赋值的? How can creating an intermediate variable change behaviour for things handled by value? 如何为值处理的事物创建中间变量更改行为?

Because when you do $array['foo'] = $array, the interpreter first adds the 'foo' index to the $array value, then puts that newly updated array inside $array['foo']. 因为当你执行$ array ['foo'] = $ array时,解释器首先将'foo'索引添加到$ array值,然后将新更新的数组放入$ array ['foo']中。

When you use an intermediate $blah, you've stored an unmodified copy of $array from before the 'foo' key was created. 当你使用中间$ blah时,你在创建'foo'键之前存储了一个未修改的$ array副本。 The intermediate doesn't change the behavior, it stores a copy of the value at the moment in time that the intermediate is created, just as it should. 中间件不会改变行为,它会在创建中间件的时刻存储值的副本,就像它应该的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM