2013-10-08 67 views
3

我无法理解为什么PHP不设置我的children财产对象,即使当我创建一个副本。PHP Unset的行事像一个参考

当我指定$singleNode = $node它不应该删除singleNode孩子,因为我没有传递引用,但它的行为是这样的。

任何人都可以为我清除它吗?

可以用PHP命令行运行这个,看看我的意思

<?php 

$node = new stdClass(); 
$node->title = 'Test'; 
$node->children = [1,2,3,4,5]; 


// Does the node have children? 
if (property_exists($node, 'children')) { 
    echo '$node has children' . PHP_EOL; 
} else { 
    echo '$node NOT has children' . PHP_EOL; 
} 

// Assign node to a new variable, and remove children 
$singleNode = $node; 
if (property_exists($singleNode, 'children')) { 
    echo '$singleNode removed children' . PHP_EOL; 
    unset($singleNode->children); 
} 


// Does the node have children? 
if (property_exists($node, 'children')) { 
    echo '$node has children' . PHP_EOL; 
} else { 
    echo '$node NOT has children' . PHP_EOL; 
} 

我发现我可以这样做:

$singleNode = clone $node

那是正确的方式做到这一点?为什么会发生?无论我将变量赋给变量,该变量是否引用内存中的相同项目?

+0

工作代码:http://codepad.org/iInMQ6o9 - 它只是@JREAM代码 - 而不是解决方案:) – Adam

+0

嘛$节点应该还是有孩子。 – JREAM

+1

查看['clone'](http://php.net/manual/en/language.oop5.cloning.php)文档。 –

回答

3

你只有一个对象。要获得第二个对象,您必须创建一个clone。从技术上来说$singleNode = $node正在复制仍然指向同一对象的oject handle。

http://php.net/manual/en/language.oop5.cloning.phphttp://php.net/manual/en/language.oop5.references.php

+0

男子我不能相信我从来没有遇到过这些年来这个问题,我想这是事实。感谢您使用链接+1和+绿色检查确认一次我被允许:) – JREAM

+1

如果“毕竟这些年”返回到PHP 4那么行为是不同的:) – johannes

+0

+1正确和恰当的文档链接! – BrianHall