148
$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?

5 Answers 5

199
$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;

3
  • 12
    I used a new DateTime in the example to demonstrate the point, but for now assume DateTime is returned from some opaque API that I can't just call over again. For example, I have a function that handles orders that returns a DateTime which is when the customer can next place an order. Calling the function to create a copy produces side effects I don't want. Apr 5, 2010 at 16:19
  • I haven't tested it actually, but it is mentioned at php.net that this is only aviable for PHP 5.3 and greater. Feb 1, 2013 at 1:02
  • @hugo: Yes, the DateTime class requires PHP 5.3. Mar 28, 2013 at 17:19
129

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
  • 1
    Thank you for the answer, but how do you know it's deep enough for DateTime? Which attributes remain references and which are copied by value? For example, I can change the time and timezone and it won't affect the clone?
    – David
    Sep 27, 2013 at 12:08
  • 1
    @David: I know it's deep enough for DateTime because I tried it, and it worked for me. I didn't try changing the timezone or any other things, just the basic time and date.
    – rjmunro
    Dec 9, 2013 at 17:49
  • 3
    Using Xdebug, var_dump($date1) reports that it contains 'date' => string, 'timezone_type' => int & 'timezone' => string. Since it doesn't appear to contain any arrays or objects, just basic scalars, a shallow clone should be fine.
    – CJ Dennis
    Jan 25, 2017 at 2:14
51

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'));
2
  • 4
    Note that unfortunately you can't just swap a DateTime with a DateTimeImmutable. There's at least IntlDateFormatter::formatObject that doesn't like immutables (returns false instead of the formatted string).
    – user276648
    Sep 14, 2016 at 3:43
  • 4
    @user276648 This bug is now fixed in php 7.1.5 php.net/ChangeLog-7.php#7.1.5
    – jontro
    May 22, 2017 at 21:00
24

TLDR (PHP 5.5+ / 7.0.0+ / 8.0.0+):

Use DateTimeImmutable: it does not alter the original instance :-)

<?php
$date1 = new DateTimeImmutable(); // Immutable => VERY IMPORTANT
$date2 = $date1->modify('+3years');
// see that $date1 still has the original year
echo $date1->format('Y-m-d H:i:s'); // outputs 2022-05-01 12:59:50
echo PHP_EOL;
echo $date2->format('Y-m-d H:i:s'); // outputs 2025-05-01 12:59:50

BTW: If you use Carbon there is also CarbonImmutable

PHP docs: https://www.php.net/manual/en/class.datetimeimmutable.php

Simple as that :)

Old answer(rewritten) (don't recommend anymore!):

Shallow copy used to be enough - Deep copy-ing DateTime didn't make sense back then, since we could easily introspect the DateTime instance and see that there were only simple types that are copied by value (there were no references).

Following code however stopped working in PHP7.4 (most likely the future solution will be somewhere around Reflection class/object),

class TestDateTime extends DateTime{
  public function test(){
   //*this* way also outputs private variables if any...
   var_dump( get_object_vars($this) );    
  }
}
$test = (new TestDateTime())->test();

used to output

array(3) {
  ["date"]=>
  string(26) "2019-08-21 11:38:48.760390"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}

so there are no references, just simple types => there was no real reason to deep copy, however I don't recommend using this anymore in the future.

4
  • I would like to see the source of clone doing shallow copy. Does it mean it is possible to do deep copy too in PHP? I thought there is just "clone" to copy object but not just reference, which for me sounds like a deep copy?
    – barell
    Sep 3, 2020 at 16:36
  • @barell not sure if I understand what you're asking, but clone keyword does shallow copy => copies simple values like ints, strings, ..., if there is a reference on another object, it copies only the reference to that object. Deep copy would mean creating a new object for each copied object etc - is it more clear now?
    – jave.web
    Sep 15, 2020 at 11:28
  • I didn't know about object references inside cloning object part. Thanks, that is very useful to know. I wish I looked into php.net/manual/en/language.oop5.cloning.php earlier!
    – barell
    Sep 15, 2020 at 11:52
  • @barell Yep it is, it is the very difference between shallow and deep copying :) Glad I could help ! :-)
    – jave.web
    Sep 15, 2020 at 12:33
1

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

2
  • 1
    This is really an answer to a different question. Sep 20, 2017 at 19:01
  • 1
    @BillyONeal I might have not explained fully how, But this is a solution to this problem as the source of this problem is how calling the method add on date2 changes the value of date1 and there is no way to copy the value of DateTime variable unless you have an DateTimeImmutable Sep 21, 2017 at 7:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.