有人会解释这个PHP开关块吗?

时间:2016-07-27 23:25:23

标签: php switch-statement

我想问一下这段代码在做什么,以及有人可以向我解释一下评论吗?

我想了解它在做什么。我猜它会根据陈述的结果在它们之间切换。 2< 1和2> 1.然后是以年月日格式设置日期?

我是在正确的轨道上吗?

switch (true) {
    case ($UserBirthday < $CurrentDate2) :
        $CurrentDate->setDate($UserBirthday->format('Y'), $CurrentDate->format('m'), $CurrentDate->format('d'));
        break;

    case ($CurrentDate2 < $UserBirthday) :
        $UserBirthday->setDate($CurrentDate->format('Y'), $UserBirthday->format('m'), $UserBirthday->format('d'));
        break;
}

$interval = $UserBirthday->diff($CurrentDate);
$difference = $interval->format('%R%a')-1; 

另外,我可以将其更改为if / else语句吗?

    if ($UserBirthday < $CurrentDate2) {
        $CurrentDate->setDate($UserBirthday->format('Y'), $CurrentDate->format('m'), $CurrentDate->format('d'));
        }

    else if ($CurrentDate2 < $UserBirthday) {
        $UserBirthday->setDate($CurrentDate->format('Y'), $UserBirthday->format('m'), $UserBirthday->format('d'));
       }


$interval = $UserBirthday->diff($CurrentDate);
$difference = $interval->format('%R%a')-1; 

2 个答案:

答案 0 :(得分:2)

虽然在代码示例中使用switch而不是if..elseif..else语句似乎没有任何好处,但通常会使用switch来代替冗长,丑陋的if..elseif..elseif..elseif..etc.语句。我怀疑这是您的代码示例的作者正在建模。

您可以在http://phpswitch.com/了解交换机的多种用途。

答案 1 :(得分:1)

实际上,我已经改变了主意,这段代码没有任何问题,虽然可能有点令人困惑。

通常,您会将变量传递给switch语句并在以下情况下比较其值:

switch($a) {
    case 1:
    // some code
    break;
}

在这种情况下,它们基本上只检查某些内容是否为真,因此它们将true传递给switch,然后每个case都是一个逻辑语句。

无论哪种方式,传入交换机的任何内容都会与==进行比较,而不是每种情况。由于switch对大型if / else有用,因此在这种情况下使用它是有效的。

然而,由于他们以大多数开发人员可能不熟悉的方式使用它,因此可能会让人感到困惑,并且一些额外的评论可能是明智之举。

但是,我错了,这段代码确实没有任何问题。