How do I deep copy a DateTime object?

匿名 (未验证) 提交于 2019-12-03 01:55:01

问题:

$date1 = $date2 = new DateTime(); $date2->add(new DateInterval('P3Y')); 

Now $date1 and $date2 contain the same date -- three years from now. I'd like to create two separate datetimes, one which is parsed from a string and one with three years added to it. Currently I've hacked it up like this:

$date2 =  new DateTime($date1->format(DateTime::ISO8601)); 

but that seems like a horrendous hack. Is there a "correct" way to deep copy a DateTime object?

回答1:

$date1 = new DateTime(); $date2 = new DateTime(); $date2->add(new DateInterval('P3Y')); 

Update:

If you want to copy rather than reference an existing DT object, use clone, not =.

$a = clone $b;



回答2:

Clone the date with the clone operator:

$date1 = new DateTime(); $date2 = clone $date1; $date2->add(new DateInterval('P3Y')); 

Clones are shallow by default, but deep enough for a DateTime. In your own objects, you can define the __clone() magic method to clone the properties (i.e. child objects) that make sense to be cloned when the parent object changes.

(I'm not sure why the documentation thinks a good example of needing to clone an object is GTK. Who uses GTK in PHP?)



回答3:

PHP 5.5.0 introduced DateImmutable. add and modify methods of this class return new objects.

$date1 = new DateTimeImmutable(); $date2 = $date1->add(new DateInterval('P3Y')); 


回答4:

You should change your DateTime to DateTimeImmutable

// from date time $date = \DateTimeImmutable::createFromMutable($mutableDate) 

then you can call any method on the DateTime without worrying about it change



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!