在PHP中,循环中定义的变量不是循环的局部变量。有没有办法销毁/取消设置每次迭代后声明的每个变量?
如果我在foreach
循环中的if
语句中声明一个变量,麻烦就来了。这个变量不一定在每次迭代时都声明,所以当我希望它被销毁时,它有可能徘徊并具有与上次相同的值!
具体来说,这是我的(简化的(代码。它解析并events.xml
包含<event>
元素的文件,这些元素都具有<startDate>
子元素,并且可能有也可能没有<endDate>
子元素,然后在循环遍历所有事件后形成显示事件的html。
<html>
<?php
$events = simplexml_load_file("events.xml");
foreach ($events as $value):
// get the start date of the current event from the xml file
$startDate = strtotime($value->startDate);
// get the end date if it exists (it might not)
$endDate = strtotime($value->endDate);
// get day of the week from the start date
$startDay = date("D", $startDate);
if ($endDate) {
$endDay = date("D", $endDate);
$dash = "-";
}
?>
<div class="event"> <!-- this is still in the foreach loop -->
<!-- insert the start day (always) followed by a dash and end day (if they exist) -->
<?php echo $startDay, $dash, $endDay; ?>
</div>
<?php endforeach; ?>
</html>
问题是,如果在events.xml
文件中,我有一个带有结束日期的事件,然后是一个没有结束日期的事件,后者的div 将具有前者的结束日(因为 $endDay
变量没有未设置(,当我根本不希望它有结束日期时。(如果 xml 文件顶部有一个事件没有结束日期,则其div 将没有结束日期。
有趣的是,对于没有结束日期的事件,$endDate
变量似乎确实在以下行被销毁:$endDate = strtotime($value->endDate);
,大概是因为它试图从 xml 中读取它但什么也没找到。但是,如果我将$endDay
声明放在 if
语句之外,那么默认情况下它会转到 01
,这是我不想要的。
您必须自己重置变量。它们在当前范围内都是可见的,循环或条件没有自己的 var 范围。
在您的情况下,您必须在每次迭代时重置$dash
和$endDay
- 即
foreach ($events as $value):
$dash = null;
$endDay = null;
//...
?>
$startDate
和$endDate
在每次迭代中都被覆盖。如果未设置$value->start/endDate
或日期无效,它们将作为值false
。