5

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,

Community
  • 1
  • 1
Leonardo
  • 2,484
  • 2
  • 25
  • 37
  • 2
    The documentation starts off with a few examples: http://php.net/manual/en/language.oop5.cloning.php Is there something there you don't fully understand? – Brad Aug 03 '11 at 14:10
  • Is not that i do not understand what the manual says, but i don't see any issue for my actual level and i would like to know of a few examples to use in later implementations. – Leonardo Aug 03 '11 at 14:13

1 Answers1

14

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.

phindmarsh
  • 879
  • 6
  • 11