为了得到当前datetime和 datetime 2天前我写了下面的代码;
$now = new \DateTime();
$twoDaysAgo = $now->sub(new \DateInterval('P2D'));
当我运行 var_dump($now, $twoDaysAgo);
结果如下。
// $now
object(DateTime)#496 (3) {
["date"]=>
string(19) "2014-08-04 16:31:08"
["timezone_type"]=>
int(3)
["timezone"]=>
string(3) "UTC"
}
// $twoDaysAgo
object(DateTime)#496 (3) {
["date"]=>
string(19) "2014-08-04 16:31:08"
["timezone_type"]=>
int(3)
["timezone"]=>
string(3) "UTC"
}
两个变量都具有相同的 $twoDaysAgo 值。为了获得所需的值,我执行了以下操作;
$now = new \DateTime();
$twoDaysAgo = new \DateTime();
$twoDaysAgo = $twoDaysAgo->sub(new \DateInterval('P2D'));
我的问题是,为什么在分配 $twoDaysAgo 之后 $now 和 $twoDaysAgo 的值相同,而不是 $now 是当前日期时间值?
最佳答案
::sub()
将更改调用它的对象,然后返回自身。
这个问题可以通过在使用它之前克隆 $now
来解决,就像这样:
$now = new \DateTime();
$twoDaysAgo = clone $now; // clone the current date object
$twoDaysAgo->sub(new \DateInterval('P2D')); // work with the clone
关于php - 当分配不同的变量时,DateTime 对象正在更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25166109/