2013-10-08 77 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