6

Why in this code my DateTime object was copied by reference it seems?
Here's my code:

<?php

date_default_timezone_set('UTC');

$dt1 = new \DateTime('2015-03-15');
$dt2 = $dt1;
$dt2 = $dt2->modify('-1 year');

echo $dt1->format('c') . PHP_EOL;
echo $dt2->format('c');

?>

I was expecting:

2015-03-15T00:00:00+00:00
2014-03-15T00:00:00+00:00

But I got this:

2014-03-15T00:00:00+00:00
2014-03-15T00:00:00+00:00
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Dannyboy
  • 1,963
  • 3
  • 20
  • 37
  • 4
    You need to use clone `$dt2 = clone $dt1;` – vaso123 Dec 15 '14 at 15:18
  • If you use the class `DateTimeImmutable` it will work, it behaves exactly the same as `DateTime` class except it never modifies itself but returns a new object instead. – Daan Dec 15 '14 at 15:22

2 Answers2

8

It's because of this line

$dt2 = $dt1;

Variables get copied, objects get referenced.

See this for an answer with examples - https://stackoverflow.com/a/6257203/1234502

You should be able to fix this with clone

Community
  • 1
  • 1
Pankucins
  • 1,690
  • 1
  • 16
  • 25
0

Consider the following text from PHP's Objects and references page:

As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object.

Basically, your $dt2 = $dt1; is simply copying the object reference and not its contents; see the response by @lolka_bolka for the appropriate means by which to perform this task.

Justin Bell
  • 396
  • 1
  • 10