可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
$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