Adventures in PHP: Object Cloning

Recently I have been experimenting with PHP. PHP is a very interesting language, to say the least. It feels a lot more like html to me than it does a traditional back end language like Ruby or Python. One of the problems that I ran into while working on some exercism exercises came while I was trying to manipulate some DateTime objects. While trying to create a new DateTime object, I did it the same way I typically would in Ruby. That is, I took the original DateTime variable ($date), and created a new variable with the same information ($newdate= $date). This caused a problem. Any changes I made to $newdate also happened to $date.

I found this to be very strange, because this would not happen in Ruby. In Ruby, assigning a new variable to an object creates a new object that is a copy of the original. So when I did (newdate = date), this would create a new object named “newdate,” and gives that object the same information as “date”. This would allow me to manipulate newdate without affecting date. In PHP, however, this is not true for DateTime. Since DateTime is not a native data type, this instead takes the ORIGINAL object, and gives it a new name. Therefore, when I modify it, I am modifying the original object.

In order to get around this, I had to use clone ($newdate = clone $date;). This takes the $date variable, and makes a new variable called $newdate. Now that $newdate is separate data, it can be modified without changing $date as well.

Things like this are interesting quirks about programming languages that I continue to discover by messing around with different languages. As my adventures into the world of programming continue, I look forward to discovering more of these things. It’s what makes the world of programming so exciting. There is always something new that you can learn.