分配其他变量时,DateTime对象将发生更改

DrC*_*lza 2 php object

为了获得当前日期时间和2天前的日期时间,我编写了以下代码;

$now        = new \DateTime();
$twoDaysAgo = $now->sub(new \DateInterval('P2D'));
Run Code Online (Sandbox Code Playgroud)

我跑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"
}
Run Code Online (Sandbox Code Playgroud)

两个变量都具有$ twoDaysAgo的相同值.为了获得所需的值,我做了以下几点;

$now        = new \DateTime();
$twoDaysAgo = new \DateTime();
$twoDaysAgo = $twoDaysAgo->sub(new \DateInterval('P2D'));
Run Code Online (Sandbox Code Playgroud)

我的问题是,在分配$ twoDaysAgo而不是现在的当前日期时间值后,为什么$ now和$ twoDaysAgo的值相同?

Cob*_*ast 7

::sub()将更改它被调用的对象,然后返回自己.
克隆$now之前可以解决这个问题,比如说:

$now        = new \DateTime();
$twoDaysAgo = clone $now; // clone the current date object
$twoDaysAgo->sub(new \DateInterval('P2D')); // work with the clone
Run Code Online (Sandbox Code Playgroud)