Linesofcode
Linesofcode

Reputation: 5903

Laravel temporary variable is being updated without interaction

I can't figure out what's being done, I have two simple variables:

$item = Clients::findOrFail($id);
$itemTemporary = $item;

Now, the variable $itemTemporary is supposed to hold the data of $item and if I have any interaction in the variable $item this $itemTemporary has nothing to do with it, right?

$item = Clients::findOrFail($id);
$itemTemporary = $item;

print_r($itemTemporary->status); // Returns TRUE

$item->status = FALSE;
$item->save();

print_r($itemTemporary->status); // Returns FALSE

How d'hell is the $itemTemporary->status being changed?

Upvotes: 1

Views: 686

Answers (2)

Don't Panic
Don't Panic

Reputation: 41820

$itemTemporary is not a copy of the $item object, but of the object identifier. (See Objects and References.) It refers to the same object. If you need to hold the data of $item temporarily while changing it, you need to use a different method such as cloning the object or converting it to an array.


Actually, I thought Laravel might have a method for this, so looked it up and apparently it does:

$itemTemporary = $item->replicate();

Upvotes: 4

domdambrogia
domdambrogia

Reputation: 2243

$itemTemporary will reference the $item object which is why you are seeing this behavior.

You can clone the object like so:

$itemTemporary = clone $item;

Upvotes: 0

Related Questions