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 inital values Oiginal object: 2020-04-14 17:14:18 Cloned object: 2020-04-14 17:14:18 Printing values after change Oiginal 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 inital values Oiginal 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 Oiginal 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.
- HTML | DOM Input Datetime Object
- How to create a copy of an object in PHP?
- How to create a shallow copy of SortedList Object in C#
- Shallow Copy and Deep Copy in C#
- PHP | Type Casting and Conversion of an Object to an Object of other class
- PHP | DateTime sub() Function
- PHP | DateTime add() Function
- PHP | DateTime createFromFormat() Function
- PHP | DateTime setDate() Function
- HTML | DOM ins dateTime Property
- PHP | DateTime modify() Function
- PHP | DateTime format() Function
- PHP | DateTime diff() Function
- HTML | datetime Attribute
- HTML | DOM del dateTime Property
- HTML | <del> datetime Attribute
- HTML | <ins> datetime Attribute
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.