cakePHP在foreach循环中的变量赋值-未知行为



这完全把我难住了。我使用Cakephp 3.9.6应用程序和PHP 7.4上的tplanner/When库来生成循环事件。在某个地方,开始日期和结束日期被设置为相同的日期。下面是我的EventsController::add方法的部分:

$data = $this->request->getData();
$copies = new When();
$copies->freq($data['frequency'])
->interval($data['interval'])
->wkst('MO');
if ($data['frequency'] == 'WEEKLY') {
$copies->byday(implode(',', $data['days']));
}
if (!empty($data['count'])) {
$copies->count($data['count']);
} else {
$copies->until(new DateTime($data['last_date'] . " 23:59:59"));
}
$copies->startDate(new DateTime($event->start->toDateTimeString()))->generateOccurrences();
$newCopies = $copies->occurrences;
$interval = $event->start->diff($event->end);
foreach ($newCopies as $copy) {
Log::debug($copy); //Shows the next date in the series calculated from start date
if ($copy == $event->start) {
continue; //First event already saved in rest of action, do not create another copy
}
$temp = $event->toArray(); //copy entity details to array
$temp['start'] = $copy; //assign new start time
$start = $copy; //thought maybe due to race condition? Copying to new object to modify end time
$temp['end'] = $start->add($interval); //$interval calculated from original event data, added to new start time
Log::debug($temp);
$result = $this->Events->newEntity($temp); //return to new entity
Log::debug($result);
$events[] = $result; //add to array of entities for saveMany()
}

我的问题是,新的开始日期在数组/实体是相同的结束日期:

Log::debug($copy)输出正确的新开始日期

Log::debug($temp)显示数组,但是start和end属性是相同的…

你不能做$start=$copy,因为它们是相同的"object"对于不同的引用,您实际上需要CLONE $copy,因此它是一个单独的对象。所以当你改变其中一个时,你不会触及另一个

最新更新