2013-11-01 53 views
3

所以我有一個奇怪的問題,其中的函數不是通過引用參數傳遞來定義的,但是對象正在以我無法解釋的方式進行更改。我已經驗證函數定義不是通過參考時間和時間再次。我從DB中檢索了一個對象。然後我對該初始對象運行分析功能。我已將該對象複製到另一個變量。然後我在副本上運行不同的分析功能,而不是原始的。運行第二個分析函數似乎改變了第一個變量對象。關於可能發生在這裏的任何想法。我一直試圖在幾個小時內調試幾個小時,我無法解釋這種行爲。我不想發佈實際功能,因爲它們是專有信息,但是,我可能會私下發送它們以獲得一些幫助。我非常感謝你的幫助。PHP通過引用問題

//get object from db 
$resp= json_decode($ln->getResponseFromDb($resultid)); 

//run pwf analysis function 
$resp = $ln->pwfBGCheck($resp); 

//show result after pwf 
print_r($resp->pwf); 

/* shows 
* stdClass Object ([status] => p [reason] => Person has no c record.) 
*/ 

//copy to another variable 
$r2 = $resp; 
//run pwf for s record other variable so it is not touching the first one! 
$r2 = $ln->pwfBGCheckSexOffender2($r2); 
echo '<BR>this is first variable<BR>'; 
print_r($resp->pwf); 
/* copies from second to first for some reason... no pass by reference on this call...  resp variable has not been touched! 
* stdClass Object ([status] => p [reason] => Person has no s record.) 
*/ 
echo '<BR>this is second<BR>'; 
print_r($r2->pwf); 
/* returns 
* stdClass Object ([status] => p [reason] => Person has no s record.) 
*/ 

回答

0

快要瘋了之後永遠... 我發現這個解決方案:

$r2 = unserialize(serialize($resp)); 

我知道是有性能損失是不理想,但我是一個最後期限並需要儘快創建一個工作解決方案。我相信這個問題仍然存在,因爲即使是被複制的變量也是通過引用傳遞的。如果有人想出一個更好的選擇,我願意接受另一個工作解決方案。謝謝!

也...因爲系列化其他一些問題(libxml的不能被序列化),這個解決方案沒有奏效... 後來我想到了

$r2 = json_decode(json_encode($resp)); 

,這實際上做的伎倆!

6

由於PHP5對象總是通過引用傳遞。如果你想獲得對象的副本,你必須使用clone

Objects and references

例外到內PHP通常的分配由值行爲發生與物體,其通過引用在PHP 5.對象分配可以經由clone關鍵字被明確地複製。

Assignment Operators

+0

但是,當我使用clone關鍵字'$ r2 = clone $ resp;'時,我仍然得到相同的結果,這非常有幫助。 –

+1

「克隆」僅爲克隆當前對象。如果你想克隆屬性對象,你必須定義'__clone'方法:this - > _ property_object = clone $ this - > _ property_object;開啓這個例子:http://us1.php.net/manual/en/language.oop5.cloning.php#example-224 – sectus

2

也可以使用json_decode($json, true);(而不是json_decode($json);)來獲得assoc array(而不是stdClass)。

而且不會引用任何問題。