Change time value of only one variable

Viewed 31

I am trying to change the time value of a variable using ->setTime in php however I also want to preserve the original time value in a separate variable. Unfortunately when I change one variable it also changes the other. Any ideas?

<?php

//creating a DateTime object
  $date = new DateTime("20-May-2015");
  $date2 = $date;

  echo $date->format("d-M-Y H:i:s") . "\n";
  echo $date2->format("d-M-Y H:i:s") . "\n";
  echo "\n";
  //setting time to a new value
  $date->setTime(5, 10);

  echo $date->format("d-M-Y H:i:s") . "\n";
  echo $date2->format("d-M-Y H:i:s") . "\n";
?>
output 
20-May-2015 00:00:00
20-May-2015 00:00:00

20-May-2015 05:10:00
20-May-2015 05:10:00 ***I want this one to stay 20-May-2015 00:00:00***

1 Answers

Objects are always passed and assigned as references. To separate them, just instantiate them as 2 objects or use the clone keyword:

$date = new DateTime("20-May-2015");

$date2 = new DateTime("20-May-2015");
// OR
$date2 = clone $date;

echo $date->format("d-M-Y H:i:s") . "\n";
echo $date2->format("d-M-Y H:i:s") . "\n";
echo "\n";
//setting time to a new value
$date->setTime(5, 10);

echo $date->format("d-M-Y H:i:s") . "\n";
echo $date2->format("d-M-Y H:i:s") . "\n";

Output:

20-May-2015 00:00:00
20-May-2015 00:00:00

20-May-2015 05:10:00
20-May-2015 00:00:00
Related