Reputation: 693
I'm quite confused about this behavior in PHP and I'm not sure, how to solve it.
I want to do this:
I generate Object
and use some methods to set its attributes. Then I want to "cache" the object, so I will store it into other variable and then I do something else with the object but it also affects cached object.
Could you give me some advice, how to do this?
Here is code snippet:
$query = new Obj();
$this->item->generateItemsQuery($query);
$this->itemsQuery = $query; // here I "cache" the variable for next usage...
// here I edit the old variable $query
if ($this->getFilter('limit') !== null) {
$query = $query->limit($this->getFilter('limit'));
}
if ($this->getFilter('page') !== null) {
$offset = ($this->getFilter('page') - 1) * $this->getFilter('limit');
$query = $query->offset($offset);
}
public function generateItemsQuery(&$query)
{
// some other things like this: $query = $query->offset($offset);
}
In this example -> problem is, that when I apply method "limit" and "offset" on $query it also affect $this->itemsQuery
Could you provide me some solution?
Thank you very much
Upvotes: 1
Views: 41
Reputation: 32714
You may want to take a look at:
http://php.net/manual/en/language.oop5.references.php
Specifically:
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.
If you want to create a clone of the object you will need to do:
$this->itemsQuery = clone $query;
See: http://php.net/manual/en/language.oop5.cloning.php
Upvotes: 2