使用 DateTime 类和 modify() 方法时日期更改



我感觉自己绕过了 PHP 原生的 \DateTime 类,但我发现了一个特殊的习惯。

$date = new DateTime(date('d-m-Y',time())); //this being todays date 21-03-2017
$first = $date->modify('first day of this month');
var_dump($first); //returns ["date"] => string(26) "2017-03-01..."
$last = $date->modify('last day of this month');
var_dump($first); //returns ["date"] => string(26) "2017-03-31..."

它似乎是通过引用分配的,因此稍后会进行修改。我怎样才能防止这种情况。

方法DateTime::modify(也添加和sub(是修改类(不要创建新的(。正如您在手册上看到的:

$date = new DateTime('2006-12-12');
$date->modify('+1 day');
echo $date->format('Y-m-d');//2006-12-13

使用新变量分配返回的日期时,仅分配引用。Wich 意味着两个变量都在查找内存中的同一对象。

$date = new DateTime('2006-12-12');
$nextDay = $date->modify('+1 day');
echo $date->format('Y-m-d');//2006-12-13
echo $nextDay->format('Y-m-d');//2006-12-13

如果要在不修改对象的情况下更改DateTime(创建新对象(,请使用日期时间不可变

$date = new DateTimeImmutable('2006-12-12');
$nextDay = $date->modify('+1 day');
echo $date->format('Y-m-d');//2006-12-12
echo $nextDay->format('Y-m-d');//2006-12-13

另一种方法是使用clone关键字:

$first = clone $last = new DateTime(date('d-m-Y',time())); //this being todays date 21-03-2017
$first->modify('first day of this month');
var_dump($first);
$last->modify('last day of this month');
var_dump($last);

代码:https://3v4l.org/rO7Zd结果:

object(DateTime)#2 (3) {
  ["date"]=>
  string(26) "2017-03-01 00:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(16) "Europe/Amsterdam"
}
object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2017-03-31 00:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(16) "Europe/Amsterdam"
}

最新更新