Home >Backend Development >PHP Tutorial > 关于PHP手册中,不推荐复杂数组的引用举的一个例子,不解,该怎么处理

关于PHP手册中,不推荐复杂数组的引用举的一个例子,不解,该怎么处理

WBOY
WBOYOriginal
2016-06-13 13:43:44772browse

关于PHP手册中,不推荐复杂数组的引用举的一个例子,不解
下面是手册里的原文:

复杂数组最好拷贝而不是引用。下面的例子不会如期望中那样工作。

PHP code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->
<?php $top = array(
    'A' => array(),
    'B' => array(
        'B_b' => array(),
    ),
);

$top['A']['parent'] = &$top;
$top['B']['parent'] = &$top;
$top['B']['B_b']['data'] = 'test';
print_r($top['A']['parent']['B']['B_b']); // array()
?> 



我输出的结果为:Array ( [data] => test ) ,这不就是预期的吗?
$top['A']['parent']为$top变量的引用,($top['A']['parent'] = &$top;)
它下边的['B']['B_b'],
不就是由$top['B']['B_b']['data'] = 'test';定义的[data] => test吗?
怎么会不如预期那样工作呢?预期怎么样工作呢?

------解决方案--------------------
看看php引用传址吧!
------解决方案--------------------
输出一下每步的结构就可以看得比较清楚:

PHP code

$top = array(
            'A' => array(),
            'B' => array(
                'B_b' => array(),
            ),
        );

        $top['A']['parent'] = &$top;
        echo '<pre class="brush:php;toolbar:false">';
        print_r($top['A']['parent']);
        echo '
'; echo '
';
        $top['B']['parent'] = &$top;
        echo '
'; echo '
';
        print_r($top['B']['parent']);
        echo '
'; echo '
';
        $top['B']['B_b']['data'] = 'test';
        print_r($top['B']['B_b']);
        echo '
'; echo '
';
        print_r($top['A']['parent']['B']['B_b']); // array()
        echo '
'; echo '
'; <div class="clear">
                 
              
              
        
            </div>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn