改变一个变量的值会影响另一个变量
每个人。我是 PHP 新手。我在 DateTime
方面遇到了这个问题:
$t1 = new DateTime();
$t1->setTime(9, 30);
$t2 = $t1;
$t2->add (new DateInterval('PT10M'));
echo $t1->format('H:i'); # outputs 9:40
如您所见,通过更改 $t2
的值,我还更改了 $t1
的值,这不是我想要的。请您告诉我为什么会发生这种情况,以及如何避免这种情况。谢谢。
伊恩
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 happening, and how to avoid it. Thank you.
Ian
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
$t1
和$t2
只是对对象的引用。当您执行$t1 = $t2
时,您只是复制引用,而不是对象。您可以改为
$t1 = clone $t2
。$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.您正在使 $t2 指向 $t1。因此,编辑 $t2 会导致您编辑 $t1 的内存。
使用克隆代替:$t2 =克隆$t1
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