0

In the following snippet, $sd is a DateTime object. It is assigned to a variable called $a. On calling add on $a, $sd also changes.

$sd = new DateTime();
$a = $sd;
$a->add(new DateInterval("P1M")); // Add 1 month to $a

This happens because $a was a reference to $sd. Is there a way, where $sd doesn't change? What should be the approach here?

1 Answers1

1

Use clone

$sd = new DateTime();
$a = clone $sd;
$a->add(new DateInterval("P1M")); // Add 1 month to $a
Daan
  • 12,099
  • 6
  • 34
  • 51