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");
}

当我调用dList::lessAnchor()$searchResult,它会修改 的属性,$searchData->Page如您所见,将其减 1,标记为(!1)。过了一会儿(下面一行),我再次打电话dList::moreAnchor()$searchResult

为什么我看到标记Page处的属性减少了 1 (!2)?我没有$searchResult通过引用。

4

1 回答 1

3

看看文档:这是预期的行为。

从 PHP 5 开始,对象变量不再包含对象本身作为值。它只包含一个对象标识符,允许对象访问者找到实际对象。当一个对象通过参数发送、返回或分配给另一个变量时,不同的变量不是别名:它们持有标识符的副本,它指向同一个对象

如果你想避免这种情况,你应该在必要的地方克隆你的对象。就像这样:

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");
}
于 2012-04-19T19:37:32.100 回答