So I'm having a weird issue with DateTimes modify() function.
I start off with a DateTime eg: 2018-08-07 12:00 & a number of days to add eg: 2.
I copy the dateTime (in variable $startDt) to a new variable ($date) so its not affected by any changes.
The modify function works fine. I get 2018-08-09 12:00. But then I want to repeat the action with a new number but the same start date. Say +3.
But it adds a total of 5! I checked and when using modify() on $date; it somehow also changes $startDt.
Can someone explain this miracle to me? :)) How does applying a function to Variable 2 affect Variable 1? Even if Variable 2 was initially a clone of Variable 1; they are supposed to be 2 separate entities...
while ($x < $duration) {
$date = $startDt;
echo "$startDt before:" . $startDt->format('Y-m-d') . "<br>";
$date = $date->modify('+' . $x . 'day');
echo "$startDt after:" . $startDt->format('Y-m-d') . "<br>";
$x++;
}
Results:
$startDt before +2 : 2018-08-08
$startDt after: 2018-08-10
$startDt before +3 : 2018-08-10
$startDt after: 2018-08-13
When assigning $startDt
to $date
the value isn't copied but referenced instead. You need to explicitly copy the object into the other variable:
# referenced
$date = $startDt;
# copied
$date = clone $startDt;
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