我无法理解为什么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
那是正确的方式做到这一点?为什么会发生?无论我将变量赋给变量,该变量是否引用内存中的相同项目?
工作代码:http://codepad.org/iInMQ6o9 - 它只是@JREAM代码 - 而不是解决方案:) – Adam
嘛$节点应该还是有孩子。 – JREAM
查看['clone'](http://php.net/manual/en/language.oop5.cloning.php)文档。 –