PHP -> A funny thing about copying & referencing objects.
So, I ran into this issue while I was working on some code for https://dree.com where I was trying to copy an object from one variable to another. Below is an example of what I was trying to do:
$order = ExisitingOrder(); // An existing order's model//Let's say Pickup Date on $order is 2021-01-01 as an example$old_order = $order;
$order->pickup_date = '2022-02-01';var_dump($order->pickup_date !== $old_order->pickup_date);
//False
Now what happened with the var_dump was that it was showing that this conditional statement was false. How could that be? We copied the $order to the $old_order variable and then changed the $order value for pickup_date.
So why on earth is this conditional statement essentially saying that both $old_order->pickup_date and $order->pickup_date are the same!?
Well, I came to find out that PHP isn’t actually copying the object, but IT IS REFERENCING the original object. So when $order changes, so does the $old_order object, since they are both pointing to the same memory address.
So how do we fix this?
PHP has a great little feature called the Object Cloning. Object cloning allows us to make a shallow copy of the Object so we can use it in the exact situation we are in. So now the code will look like this:
$order = ExisitingOrder(); // An existing order's model//Let's say Pickup Date on $order is 2021-01-01 as an example$old_order = clone $order;$order->pickup_date = '2022-02-01';var_dump($order->pickup_date !== $old_order->pickup_date);
//True
As you can see, we added the clone keyword to the $order object when assigning it to the $old_order variable. So, when we change the properties on the $order object, the $old_order object now stays static. We are now getting the desired results as we were expecting.
Full transparency, I am not sure if this is a bug in the Phalcon framework, or if this is something that PHP has had an issue with for years. Either way I have tested this code above and it has worked for me, and I hope that it works for you too.
Happy Coding!