Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Why is DateTime object copied by reference in my code? [duplicate]

Tags:

php

datetime

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
like image 286
Dannyboy Avatar asked Dec 15 '14 15:12

Dannyboy


People also ask

Does PHP pass Objects by reference?

In PHP, objects are passed by references by default. Here, reference is an alias, which allows two different variables to write to the same value. An object variable doesn't contain the object itself as value.

How do I copy a DateTime object?

A copy of DateTime object is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly. When an object is cloned, PHP will perform a shallow copy of all of the object's properties.

Are Datetimes immutable Python?

The date , datetime , time , and timezone types share these common features: Objects of these types are immutable.


1 Answers

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

like image 195
Pankucins Avatar answered Nov 10 '22 10:11

Pankucins