DateTime Modify() php affecting previous variable [duplicate]

﹥>﹥吖頭↗ 提交于 2020-07-03 06:55:29

问题


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

回答1:


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;


来源:https://stackoverflow.com/questions/51842830/datetime-modify-php-affecting-previous-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!