-1

I have the following code:

foreach($this->items as $item) {
            
    echobr("a item price: " . $item->price);
    $duplicate = $item;
    $duplicate->price = 0;
    $duplicate->type = "Discount Item";

    echobr("b item price: " . $item->price);
    echobr("c dup item price: " . $duplicate->price);
        // Duplicate new item to cart
        $this->AddItem($duplicate);
}

And the output I get is:

a item price: 10
b item price: 0
c dup item price: 0

So for some reason, changing the price on the temporary variable $duplicate changes the price on $this-items, but I dont know why? I thought to do that you'd need the use a reference variable, such as &$items ?

4
  • You need to clone the object. That's how it works in many languages, not just PHP. Feb 11, 2021 at 15:17
  • @ÁlvaroGonzález How do I clone? And why can't I just make a copy like a normal variable? And so am I right, is duplicate just a pointer or reference variable?
    – Chud37
    Feb 11, 2021 at 15:17
  • because the "operator =" create a reference, in other words, the $duplicate is just an alias of $item Feb 11, 2021 at 15:18
  • @Berto99 but why is it that way with objects, and not variables?
    – Chud37
    Feb 11, 2021 at 15:19

1 Answer 1

3

Objects are copied by reference. So $duplicate points to $item in memory. Change one, you change them both.

To get a new object, you must clone the original object.

$duplicate = clone $item;
4
  • Wow, I've never seen that before, in all my years of coding! Thank you so much!
    – Chud37
    Feb 11, 2021 at 15:18
  • I asked above, but why is = copy by reference with objects, but not with variables?
    – Chud37
    Feb 11, 2021 at 15:28
  • 1
    Good question. PHP really is just following the lead of other languages here. I am guessing this has to do with better memory usage as objects can be larger in memory than typical scalar variables.
    – John Conde
    Feb 11, 2021 at 15:31
  • Wow well thank you. I've not done a huge amount of OOP programming in PHP, so this was new to me. Its lovely to learn something new.
    – Chud37
    Feb 11, 2021 at 15:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.