<?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");
}
当我在dList::lessAnchor()
上致电$searchResult
时,它会将$searchData->Page
的属性修改为1,如您所见,将其减少1,标记为(!1)
。
过了一会儿(下面一行),我再次在dList::moreAnchor()
上致电$searchResult
。
为什么我会在Page
标记处看到(!2)
属性减少1?我没有通过引用传递$searchResult
。
答案 0 :(得分: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");
}