2012-04-19 129 views
2
<?php 

// $searchResult is type of Outcome 
// This is what we do: 
dList::lessAnchor($searchResult)->showElement(); 
dList::moreAnchor($searchResult)->showElement(); 

/** 
* @returns vAnchor (can get showed with showElement() - not part of the problem) 
*/ 
public static function lessAnchor(Outcome $searchResult){ 
    $searchData = $searchResult->searchData; 
    $searchData->Page = $searchData->Page - 1; // (!1) 
    return self::basicAnchor($searchData, "Back"); 
} 

/** 
* @returns vAnchor (can get showed with showElement() - not part of the problem) 
*/ 
public static function moreAnchor(Outcome $searchResult){ 
    $searchData=$searchResult->searchData; 
    $searchData->Page = $searchData->Page + 1; // (!2) 
    return self::basicAnchor($searchData, "More"); 
} 

當我呼籲$searchResultdList::lessAnchor(),它由1降低它修改的$searchData->Page屬性正如你看到的,在標註符合(!1)。 經過一段時間(下面一行),我再次撥打$searchResult致電dList::moreAnchor()爲什麼會發生這種情況與我的變量?

爲什麼我看到Page屬性在(!2)標記處減1?我沒有通過參考$searchResult

回答

3

看看the documentation:這是打算的行爲。

從PHP 5開始,對象變量不再包含對象本身作爲值。它只包含一個對象標識符,它允許對象訪問器找到實際的對象。 當一個對象被自變量發送,返回或分配給另一個變量時,不同的變量不是別名:他們持有標識符的副本,它指向相同的對象

如果你想避免這種情況,你應該在哪裏需要clone your object。它就像這樣:

public static function lessAnchor(Outcome $searchResult){ 
    $searchData = clone $newResult->searchData; //$searchData now is a new object 
    $searchData->Page=$searchData->Page-1; // (!1) 
    return self::basicAnchor($searchData,"Back"); 
} 
+0

哇,現在我沒有想到這一點。我應該在函數調用中克隆對象嗎? - 好吧,我明白了。謝謝你的建議和質量 – Dyin 2012-04-19 19:40:50

+0

是的 - 我剛剛編輯我的答案,提到這一點;) – oezi 2012-04-19 19:42:40

相關問題