DateTime Modify()PHP影响先前的变量 [英] DateTime Modify() php affecting previous variable

查看:61
本文介绍了DateTime Modify()PHP影响先前的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在使用DateTimes Modify()函数时遇到了一个奇怪的问题。

So I'm having a weird issue with DateTimes modify() function.

我从DateTime开始,例如:2018-08-07 12:00& ;要添加的天数,例如:2。

I start off with a DateTime eg: 2018-08-07 12:00 & a number of days to add eg: 2.

我将dateTime(在变量$ startDt中)复制到新变量($ date)中,因此不受任何更改的影响

I copy the dateTime (in variable $startDt) to a new variable ($date) so its not affected by any changes.

修改功能可以正常工作。我得到2018-08-09 12:00但是,然后我想用一个新的编号但开始日期相同的动作重复该动作。说+3。

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.

但是总共加了5!我检查并在$ date上使用modify()时;

But it adds a total of 5! I checked and when using modify() on $date; it somehow also changes $startDt.

有人可以向我解释这个奇迹吗? :))将函数应用于变量2如何影响变量1?即使变量2最初是变量1的副本;它们应该是2个独立的实体...

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++;

    }

结果:

$startDt before +2 : 2018-08-08
$startDt after: 2018-08-10
$startDt before +3 : 2018-08-10
$startDt after: 2018-08-13


推荐答案

$ startDt 分配给 $ date 时,该值不会被复制,而是被引用。您需要将对象明确复制到另一个变量中:

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;

这篇关于DateTime Modify()PHP影响先前的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆