2012-04-19 128 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

相关问题