下面的代码说明了 PHP 引用的奇怪行为:
<?php
function this_works()
{
$root = array('name'=>'root', 'children'=>array());
$level_1 = array('name'=>'level_1', 'children'=>array());
$item1 = array('name'=>'level_2_1', 'children'=>array());
$item2 = array('name'=>'level_2_2', 'children'=>array());
$croot = &$root;
$croot['children'][] = &$level_1;
$croot = &$level_1;
$croot['children'][] = &$item1;
$croot['children'][] = &$item2;
$croot = &$root;
print_r($croot);
}
function this_fails()
{
$root = array('name'=>'root', 'children'=>array());
$level_1 = array('name'=>'level_1', 'children'=>array());
$item1 = array('name'=>'level_2_1', 'children'=>array());
$item2 = array('name'=>'level_2_2', 'children'=>array());
$croot = &$root;
$stack = array();
$croot['children'][] = &$level_1;
$crootref = &$croot;
array_push($stack, $crootref);
$croot = &$level_1;
$croot['children'][] = &$item1;
$croot['children'][] = &$item2;
# this works, assignment below - doesn't... WHY?
#$x = array_pop($stack);
#var_dump($x);
$croot = array_pop($stack);
print_r($croot);
}
this_works();
echo "------------------\n";
this_fails();
?>
第一个函数提供了预期的结果,而第二个函数失败并声称递归循环:
Array
(
[name] => root
[children] => Array
(
[0] => Array
(
[name] => level_1
[children] => Array
(
[0] => Array
(
[name] => level_2_1
[children] => Array
(
)
)
[1] => Array
(
[name] => level_2_2
[children] => Array
(
)
)
)
)
)
)
------------------
Array
(
[name] => root
[children] => Array
(
[0] => Array
(
[name] => root
[children] => Array
*RECURSION*
)
)
)
奇怪的是,如果在第二个函数中,中间变量将用于从堆栈中获取值,结果又可以了。我不明白发生了什么事。由于一个assinment,我如何多次获得根元素作为其自身的子元素?
最初,我需要从 XML 构建树(使用 sax 解析器)并打算让“当前根”指向当前级别的树节点,并将其推入/弹出堆栈并向其中添加子元素,但是,令人惊讶的是,由于上述两个函数显示的问题,我未能实施此方案。
那么,这种方法有什么问题呢?