Dyin
Dyin

Reputation: 5376

Why is this happening with my variables?

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

When I call dList::lessAnchor() on $searchResult, it modifies the property of $searchData->Page by decreasing it by 1 as you see, marked at line with (!1). After a while (one line below), I call dList::moreAnchor() on $searchResult again.

Why do I see Page attribute decreased by 1 at (!2) mark? I did not pass $searchResult by reference.

Upvotes: 2

Views: 60

Answers (1)

oezi
oezi

Reputation: 51817

take a look at the documentation: this is intended behaviour.

As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

if you want to avoid this, you should clone your object where neccessary. it's just like this:

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

Upvotes: 3

Related Questions