How do I deep copy a DateTime object?
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?)
PHP 5.5.0 introduced DateTimeImmutable. add and modify methods of this class return new objects.
$date1 = new DateTimeImmutable();$date2 = $date1->add(new DateInterval('P3Y'));