$date = new DateTime('2021-04-01'); $date_copy = clone $date; echo $date->format('Y-m-d'); // Output: 2021-04-01 echo $date_copy->format('Y-m-d'); // Output: 2021-04-01
$date = new DateTime('2021-04-01'); $date_copy = clone $date; $date_copy->modify('+1 day'); echo $date->format('Y-m-d'); // Output: 2021-04-01 echo $date_copy->format('Y-m-d'); // Output: 2021-04-02In both cases, the DateTime object `$date` remains unchanged after making a copy. This is achieved using the clone keyword to create a new object that is identical to the original one. Package library: PHP Standard Library (included in PHP core)