How to copy a DateTime object in PHP ?
Given a DateTime object and the task is to create a copy of that object. To create a copy of DateTime object we use clone keyword which is described below:
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. Any properties that are references to other variables will remain references.
$DateTime_copy_object_name = clone $DateTime_object_to_be_copied
Below examples illustrate the cloning of DateTime object in PHP:
Printing initial values Original object: 2020-04-14 17:14:18 Cloned object: 2020-04-14 17:14:18 Printing values after change Original object: 2020-04-17 17:14:18 Cloned object: 2020-04-14 17:14:18
Example 2: Below program distinguishes clone from assignment ( = ) operator.
Printing initial values Original object: 2020-04-14 17:14:49 Reference object: 2020-04-14 17:14:49 Cloned object: 2020-04-14 17:14:49 Printing values after change Original object: 2020-07-14 17:14:49 Reference object: 2020-07-14 17:14:49 Cloned object: 2020-04-14 17:14:49
So, to make a copy of the object we use clone, don’t use (=) operator as it creates a reference.