Why do both variables change after – & gt; modify?
& lt;? php
$ date = new DateTime ();
echo $ date- & gt; format ('d.m G: i'). "\ n";
$ near = $ date;
$ near- & gt; modify ('+ 1 day');
echo $ near- & gt; format ('d.m'). "\ n";
echo $ date- & gt; format ('d.m');
? & gt;
Answer 1, authority 100%
Why shouldn’t they?
You have an object of class DateTime
and two references to it: near
and date
. But the object is still one, so changes to the object will of course be visible through both references to it.
https://www.php.net/manual/en /language.oop5.references.php
A PHP reference is an alias, which allows two different variables to write to the same value. In PHP, an object variable doesn’t contain the object itself as value. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.
Perhaps you need cloning or DateTimeImmutable
class whose modify
method will spawn a new object.
Answer 2, authority 50%
because this is not a copy
$ near = $ date;
and assignment
After this line, both variables refer to the same DateTime
object
Answer 3
Thank you.
& lt;? php
$ date = new DateTime ();
echo $ date- & gt; format ('d.m'). "\ n";
$ near = clone $ date;
$ near- & gt; modify ('+ 1 day');
echo $ near- & gt; format ('d.m'). "\ n";
echo $ date- & gt; format ('d.m');
? & gt;