Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone PHP example usages [duplicate]

Tags:

oop

clone

php

Possible Duplicate:
what is Object Cloning in php?

I am kind of new to Object oriented development, i am creating an application as an object oriented program, can you please provide me a few examples about how is normally used the clone method of PHP, real life examples preferred.

I would like to understand more fully the concepts related.

Thanks,

like image 481
Leonardo Avatar asked Aug 03 '11 14:08

Leonardo


1 Answers

Here is an example where I needed to clone an object the other day. I needed to have two DateTime objects, a from date and a to date. It was possible for them to be specified in URL arguments, however either could be omitted and I would need to set them to a default value.

The example below has been simplified somewhat, so there are flaws in the implementation as it's presented below, however it should give you a decent idea.

The problem lies in the DateTime::modify method. Lets assume the user has provided a from date, but not a to date. Because of this we set the to date to be 12 months from the given from date.

// create the from date from the URL parameters
$date_from = DateTime::createFromFormat('d/m/Y', $_GET['from']);

The DateTime class features a method to modify itself by some offset. So one could assume the following would work.

$date_to = $date_from;
$date_to->modify('+12 months');

However, that would cause both $date_from and $date_to to be the same date, even though the example appears to copy the variable $date_from into $date_to, its actually creating a reference to it, not a copy. This means that when we call $date_to->modify('+12 months') its actually modifying both variables because they both point to the same instance of the DateTime object.

The correct way to do this would be

$date_to = clone $date_from; // $date_to now contains a clone (copy) of the DateTime instance $date_from
$date_to->modify('+12 months');

The clone statement tells PHP to create a new instance of the DateTime object and store it in $date_to. From there, calling modify will change only $date_to and $date_from will remain unchanged.

like image 128
phindmarsh Avatar answered Oct 04 '22 17:10

phindmarsh