Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
875 views
in Technique[技术] by (71.8m points)

cakephp - PHP variable assignment in foreach loop - unknown behavior

This has me completely stumped. I am using a Cakephp 3.9.6 application and tplaner/When library on PHP 7.4 to generate recurring events. Somewhere, the start and end dates are being set as the same date. Here is the section from my EventsController::add method:

$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()
}

The problem I have is that the new start date in the array/entity are the same as the end date:

Log::debug($copy) outputs the correct new start date

Log::debug($temp) shows the array, but the start and end properties are the same...

question from:https://stackoverflow.com/questions/66068666/php-variable-assignment-in-foreach-loop-unknown-behavior

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can not do $start=$copy as they will be the same "object" with different references, you actually want to CLONE $copy so it is a separate object. So when you alter one you do not touch the other


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...