Why in this code my DateTime object was copied by reference it seems?
Here's my code:
<?php
date_default_timezone_set('UTC');
$dt1 = new \DateTime('2015-03-15');
$dt2 = $dt1;
$dt2 = $dt2->modify('-1 year');
echo $dt1->format('c') . PHP_EOL;
echo $dt2->format('c');
?>
I was expecting:
2015-03-15T00:00:00+00:00
2014-03-15T00:00:00+00:00
But I got this:
2014-03-15T00:00:00+00:00
2014-03-15T00:00:00+00:00
In PHP, objects are passed by references by default. Here, reference is an alias, which allows two different variables to write to the same value. An object variable doesn't contain the object itself as value.
A copy of DateTime object is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly. When an object is cloned, PHP will perform a shallow copy of all of the object's properties.
The date , datetime , time , and timezone types share these common features: Objects of these types are immutable.
It's because of this line
$dt2 = $dt1;
Variables get copied, objects get referenced.
See this for an answer with examples - https://stackoverflow.com/a/6257203/1234502
You should be able to fix this with clone
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With