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

PHP variable assignment in foreach loop - unknown behavior

这让我完全难住了。我在 PHP 7.4 上使用 Cakephp 3.9.6 应用程序和 tplaner/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()
}

我遇到的问题是 array/entity 中的新开始日期与结束日期相同:

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

Log::debug($temp)显示数组,但是开始和结束属性是一样的...

你不能做 $start=$copy 因为它们将是具有不同引用的同一个“对象”,你实际上想要 CLONE $copy 所以它是一个单独的对象。所以当你改变一个时,你不会碰到另一个