开发者

Changing value of a variable effects another variable

everyone. I am new to PHP. I am having this problem with DateTime:

  $t1 = new DateTime();
  $t1->setTime(9, 30);
  $t2 = $t1;
  $t2->add (new DateInterval('PT10M'));
  echo $t1->format('H:i'); # outputs 9:40

As you can see, by changing the value of $t2, I also changed the value of $t1, which is not what I want. Would you please tell me why is this happen开发者_运维百科ing, and how to avoid it. Thank you.

Ian


$t1 and $t2 are just reference to an object. When you do $t1 = $t2, you are just copying the reference, not the object.

You could to $t1 = clone $t2 instead.


You are causing $t2 to point to $t1. So editing $t2 causes you to edit the memory of $t1.

Use clone instead: $t2 = clone $t1


You should use

$t2 = clone $t1;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜