Domanda

Here is an example of the code I used:

<?php 
date_default_timezone_set("Europe/London");
$date1 = date_create("2014-04-05");
$date2 = $date1;
date_add($date2, new DateInterval("P1M"));
echo "Date 1: ".date_format($date1, "Y-m-d")."<br/>";
echo "Date 2: ".date_format($date2, "Y-m-d")."<br/>";
?>

The result for this would be:

Date 1: 2014-05-05
Date 2: 2014-05-05

I was expecting the result of:

Date 1: 2014-04-05
Date 2: 2014-05-05

How can I get the expected result and fix this? I can only use PHP, HTML and CSS so no jQuery or Javascript please.

È stato utile?

Soluzione

The clone keyword is what you need.

$date2 = clone $date1;

When an object is cloned, a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references.

If your object $date2 holds a reference to another object $date1 which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.

Source

Altri suggerimenti

This is due to how objects are assigned by reference since PHP 5; after assignment, changes made to one object are reflected in the other as well.

The generic solution is to clone the object:

$date2 = clone $date1;

In this case you could also use the DateTimeImmutable interface (introduced in 5.5) which creates new instances whenever you attempt to modify it, e.g. using ->add().

$date1 = new DateTimeImmutable('2014-04-05');
$date2 = $date1;

$date2 = $date2->add(new DateInterval('P1M'));

echo "Date 1: ".date_format($date1, "Y-m-d")."<br/>";
echo "Date 2: ".date_format($date2, "Y-m-d")."<br/>";

This code can be made easier by doing this:

$date1 = new DateTimeImmutable('2014-04-05');
$date2 = $date1->add(new DateInterval('P1M'));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top