Вопрос

I would like to calculate with PHP the start and end datetime of an event. I get the start of this event and the duration to add to get the end. So I tried the following code:

$startTime = $this->getStartTime();
$endTime = $this->getStartTime();

$endTime->add(new DateInterval('PT75M'));

in this example I add 75 minutes to the start time and I calculate the end of the event. It works, however it edits also the start time. I read in the PHP docs that the ADD method edits the object which is called on but I don't understand how it could edit the startEdit variable. I don't use reference in any of the methods that I wrote in the example, neither in the getStartTime function

Это было полезно?

Решение

You have to create a new DateTime instance for that or you will be editing your original reference to your start date DateTime object. Try something like this:

$endTime = clone $startTime;
$endTime->add(new DateInterval('PT75M'));

Другие советы

If it is possible to change getStartTime() method's return type, I highly recommend changing it from \DateTime to \DateTimeImmutable.

Then the code will go as follows:

$endTime = $startTime->add(new DateInterval('PT75M'));

More examples and advantages of this approach are described pretty well in this Nikola Poša's blog article.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top