문제

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