PHP Why is a DateTime object copied by reference in my code?

Why was the DateTime object copied by reference in this code? Here is 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 expected:

 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 
+5
source share
2 answers

This is because of this line

 $dt2 = $dt1; 

Variables are copied, objects get a link.

See this for an answer with examples - fooobar.com/questions/116618 / ...

You can fix it with clone

+5
source

Consider the following text from a PHP page of objects and links :

Starting in PHP 5, the object variable no longer contains the object as a value. It contains only the object identifier, which allows object accessories to find the actual object.

Basically, your $dt2 = $dt1; just copies the link to the object, not its contents; see @ lolka_bolka answer for appropriate ways to accomplish this task.

0
source

Source: https://habr.com/ru/post/1209117/


All Articles