我维护了一些遗留代码,并且我一直在删除对新对象的引用,如:
$object = & new SomeObject();
到此:
$object = new SomeObject();
而且,尽管事实上它不应该有任何区别,因为PHP5确实搞砸了一些非常糟糕的东西,而对象根本不再是一个参考。如果&
被替换,则问题就会消失。
以下是一个示例代码:
<?php
class TreeNode
{
public $subtree;
public $name;
public $layer;
public $children;
function &addNode(&$node)
{
$this->children[] = &$node;
}
}
$subtree = array(array('bla','blubb'), 'foo');
$tree = new TreeNode();
$tree->subtree = $subtree;
$tree->layer = 0;
$tree->name = 'root';
$b = buildTree($tree);
print_r($b);
function &buildTree(&$tree) {
if(is_array($tree->subtree))
{
foreach($tree->subtree as $key => $subtree)
{
$node = new TreeNode(); ///#### This line is a toggle and it's unknown why
$node->layer = $tree->layer + 1;
$node->subtree = $subtree;
$tree->addNode( buildTree($node) );
unset($tree->subtree[$key]);
}
}
else
{
$tree->name = $tree->subtree;
}
return $tree;
}
?>
如果该行为$node = new TreeNode();
,则输出为:
TreeNode对象
(
[subtree] =&gt;排列
(
)
[name] => root
[layer] => 0
[children] => Array
(
[0] => TreeNode Object
(
[subtree] => foo
[name] => foo
[layer] => 1
[children] =>
)
[1] => TreeNode Object
(
[subtree] => foo
[name] => foo
[layer] => 1
[children] =>
)
)
)
如果该行为$node = & new TreeNode();
,则输出为:
TreeNode对象
(
[subtree] =&gt;排列
(
)
[name] => root
[layer] => 0
[children] => Array
(
[0] => TreeNode Object
(
[subtree] => Array
(
)
[name] =>
[layer] => 1
[children] => Array
(
[0] => TreeNode Object
(
[subtree] => bla
[name] => bla
[layer] => 2
[children] =>
)
[1] => TreeNode Object
(
[subtree] => blubb
[name] => blubb
[layer] => 2
[children] =>
)
)
)
[1] => TreeNode Object
(
[subtree] => foo
[name] => foo
[layer] => 1
[children] =>
)
)
)
答案 0 :(得分:0)
实际上,事实证明这是一个由更多参考文献引起的问题。有问题的代码看起来像这样:
function &recursiveFunction(&$someobject) {
$object = & new SomeObject();
$someobject->recursiveFunction($object);
return $someobject;
}
从函数中删除引用以及使用对象的任何地方最终解决了问题,而无需对创建进行引用。因此,这只是参考本身的一部分问题,也是其他参考文献。
function recursiveFunction($someobject) {
$object = new SomeObject();
$someobject->recursiveFunction($object);
return $someobject;
}
我仍然不确定究竟为什么会发生这种情况,但即使在较新的版本中,处理&$object
的PHP内部问题仍可能与$object
有所不同对象应该始终是对象本身的引用。