如何防止在其引用更改时更改原始对象?

How to prevent changing the original object when its reference changes?

在以下代码段中,$sd 是一个 DateTime 对象。它被分配给一个名为 $a 的变量。在 $a 上调用 add 时,$sd 也会发生变化。

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

发生这种情况是因为 $a 是对 $sd 的引用。有没有办法,$sd 不会改变?这里的方法应该是什么?

使用clone

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