PHP switch 和 case 逻辑控制
可以对案例进行逻辑控制吗?
即:
$v = 0;
$s = 1;
switch($v)
{
case $s < $v:
// Do some operation
break;
case $s > $v:
// Do some other operation
break;
}
有没有办法做类似的事情?
It possible to have logical control on case ?
ie:
$v = 0;
$s = 1;
switch($v)
{
case $s < $v:
// Do some operation
break;
case $s > $v:
// Do some other operation
break;
}
Is there a way to do something similar ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
传递给 switch 的条件是与案例进行比较的值。条件(在你的问题 $v 中)被评估一次,然后 PHP 寻找第一个与结果匹配的情况。
来自手册(在示例#2之后),添加了强调:
在您的问题中,
switch ($v)
与您编写的相同:switch (0)
,因为$v = 0
。然后,您的交换机将尝试找到等于 0 的情况。并且,正如 @Kris 所说:如果您必须在 case 语句中使用条件,则您的 switch 条件应该是布尔值,例如:
现在您的 switch 尝试寻找第一个计算结果为
true
的 case,在本例中为$s> $v
。请注意,虽然 switch-condition 仅评估一次,但每个 case 都会按顺序评估:
与 default-case 相呼应“2”,因为当将 $a 与“2”进行比较时,$a 为 1 并且该 case 被丢弃; while:
回显案例“2”中的“two”,因为
++$a > 2
增加 $a 但不匹配 $a。default
是一个后备,它的位置并不重要。注意:上述开关既晦涩又深奥,仅作为证明示例提供。
The condition that is passed to switch is a value the cases are compared against. The condition (in your question $v) is evaluated once and then PHP seeks for the first case that matches the result.
From the manual (after Example #2), emphasis added:
In your question
switch ($v)
is same as if you'd written:switch (0)
, because$v = 0
. Then, your switch will try to find a case which equals to 0. And, just as @Kris said:If you have to use conditions in case statements, your switch-condition should be a boolean, e.g.:
Now your switch tries to seek the first case that evaluates to
true
, which in this case would be$s > $v
.Note that while the switch-condition is evaluated only once, cases are each evaluated in order:
echoes '2' from default-case, because when comparing $a to "2" $a was 1 and the case is discarded; while:
echoes 'two' from case '2' because
++$a > 2
increases $a but doesn't match $a.default
is a fallback and its position doesn't matter.NB: the aforementioned switches are fugly and esoteric and are only provided as a proof-of-example.
这是行不通的,每种情况都需要是标量值。在你的例子中,情况更糟,它可能看起来有效,但是......
$s < $v 的计算结果为 false,这会在 $v 上触发,因为它在这里为 0。
This will not work, every case needs to be a scalar value. in your example case it is even worse, it may seem to work but...
$s < $v evaluates to false, which triggers on the $v because it is 0 in here.
不是最易读的用法,但是是的,你可以。
如果您确实需要简单的比较,请使用 if/else - if/elseif/else 结构。
Not the most readable use of, but yes you can.
Use if/else - if/elseif/else structure if you do need just a simple comparison.
http://php.net/manual/en/control-structs.elseif.php
http://php.net/manual/en/control-structures.elseif.php