当我向日期时间添加间隔时,PHP 似乎会改变其他日期时间变量。为什么?
When I add an interval to a datetime, PHP seems to alter other datetime variables. Why?
我真的不知道怎么问这个。
我在两个变量中保存了相同的日期。
然后我将 100 天添加到第二个变量。
但两者似乎都发生了变化。为什么会这样?
$begin = new DateTime("20180101");
$end = $begin;
$end = $end->add(new DateInterval('P100D'));
echo $begin->format('Y-m-d') . "<br>";
echo $end->format('Y-m-d');
结果是:
2018-04-11
2018-04-11
但我预计:
2018-01-01
2018-04-11
如果你想使用同一个 DateTime 对象来设置不同的日期,你必须这样做:
$begin = new DateTime("20180101");
$end = clone $begin;
$end = $end->add(new DateInterval('P100D'));
echo $begin->format('Y-m-d') . "<br>";
echo $end->format('Y-m-d');
至于为什么:PHP 通过引用使用同一个对象...
如果您通过 new DateTime('pattern') 创建两个不同的 DateTime 对象,它将表现得很好。
您现在看到的行为也可以这样观察:
$test = new stdClass();
$test->sample = "What!?";
$another = $test;
$another->sample = "Impossibru!";
echo $another->sample . "<br>";
echo $test->sample . "<br>";
我真的不知道怎么问这个。
我在两个变量中保存了相同的日期。 然后我将 100 天添加到第二个变量。 但两者似乎都发生了变化。为什么会这样?
$begin = new DateTime("20180101");
$end = $begin;
$end = $end->add(new DateInterval('P100D'));
echo $begin->format('Y-m-d') . "<br>";
echo $end->format('Y-m-d');
结果是:
2018-04-11
2018-04-11
但我预计:
2018-01-01
2018-04-11
如果你想使用同一个 DateTime 对象来设置不同的日期,你必须这样做:
$begin = new DateTime("20180101");
$end = clone $begin;
$end = $end->add(new DateInterval('P100D'));
echo $begin->format('Y-m-d') . "<br>";
echo $end->format('Y-m-d');
至于为什么:PHP 通过引用使用同一个对象... 如果您通过 new DateTime('pattern') 创建两个不同的 DateTime 对象,它将表现得很好。
您现在看到的行为也可以这样观察:
$test = new stdClass();
$test->sample = "What!?";
$another = $test;
$another->sample = "Impossibru!";
echo $another->sample . "<br>";
echo $test->sample . "<br>";