Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime Modify() php affecting previous variable [duplicate]

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
like image 816
Frenchmassacre Avatar asked Dec 08 '22 14:12

Frenchmassacre


1 Answers

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;
like image 107
asynts Avatar answered Dec 11 '22 08:12

asynts