Clone PHP example usages [duplicate]
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 mor开发者_StackOverflow中文版e fully the concepts related.
Thanks,
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.
精彩评论