如何深入复制DateTime对象? [英] How do I deep copy a DateTime object?
本文介绍了如何深入复制DateTime对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ date1 = $ date2 = new DateTime();
$ date2-> add(new DateInterval('P3Y'));
现在 $ date1
和 $ date2
包含相同的日期 - 三年后。我想创建两个单独的数据时间,一个从一个字符串中解析出来,一个添加三年。目前我已经这样砍了它:
$ date2 = new DateTime($ date1-> format(DateTime :: ISO8601));
但这似乎是一个可怕的黑客。是否有一个正确的深度复制DateTime对象的方法?
解决方案
$ date1 = new DateTime();
$ date2 = new DateTime();
$ date2-> add(new DateInterval('P3Y'));
更新:
如果要复制而不是引用现有的DT对象,请使用克隆
,而不是 =
。 p>
$ a = clone $ b;
$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?
解决方案
$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;
这篇关于如何深入复制DateTime对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文