The method DateTime::modify (add and sub also) is to modify the class (don't to create a new own). As you can see on the manual:
$date = new DateTime('2006-12-12');
$date->modify('+1 day');
echo $date->format('Y-m-d');//2006-12-13
When you assign the returned date with a new variable, you're assigning only a reference. Wich means that both variables are looking to the same object in memory.
$date = new DateTime('2006-12-12');
$nextDay = $date->modify('+1 day');
echo $date->format('Y-m-d');//2006-12-13
echo $nextDay->format('Y-m-d');//2006-12-13
If you want to change a DateTime
without modifying the object (creating a new one) use DateTimeImmutable
$date = new DateTimeImmutable('2006-12-12');
$nextDay = $date->modify('+1 day');
echo $date->format('Y-m-d');//2006-12-12
echo $nextDay->format('Y-m-d');//2006-12-13
Another approach is with clone
keyword:
$first = clone $last = new \DateTime(date('d-m-Y',time())); //this being todays date 21-03-2017
$first->modify('first day of this month');
var_dump($first);
$last->modify('last day of this month');
var_dump($last);
Code: https://3v4l.org/rO7Zd
Result:
object(DateTime)#2 (3) {
["date"]=>
string(26) "2017-03-01 00:00:00.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Amsterdam"
}
object(DateTime)#1 (3) {
["date"]=>
string(26) "2017-03-31 00:00:00.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(16) "Europe/Amsterdam"
}