$bytes = 0;
switch($bytes){
case $bytes == 0:
echo 'Equal to 0.';
break;
case $bytes < 0:
echo 'Less than 0.';
break;
}
这将输出“小于 0”。
为什么?
$bytes = 0;
switch($bytes){
case $bytes == 0:
echo 'Equal to 0.';
break;
case $bytes < 0:
echo 'Less than 0.';
break;
}
这将输出“小于 0”。
为什么?
switch声明不是那样工作的。检查 each 时case,会将值与值进行比较case(使用==)。
所以,PHP 正在做:
$bytes == ($bytes == 0)?即:$bytes == (true)。这是false,所以它被跳过了。$bytes == ($bytes < 0)?即:$bytes == (false)。这是true,所以它运行那个块。你需要在if/else这里使用。
$bytes = 0;
if($bytes == 0){
echo 'Equal to 0.';
}
elseif($bytes < 0){
echo 'Less than 0.';
}
一个老问题,但还有另一种使用 switch 的方法 :) 我在 SitePoint 上找到了它!
switch (true) {
case $bytes == 0: // result of this expression must be boolean
echo 'Equal to 0.';
break;
case $bytes < 0: // result also must be boolean
echo 'Less than 0.';
break;
default:
}
说明: iftrue == ($bytes == 0)或 if true == ($bytes > 0)ordefault:
你可以使用switch (false) {}if you have many falsy results 而不是x != y
您不能在 switch 语句中使用运算符。它实际上应该是:
$bytes = 0;
switch($bytes){
case 0:
echo 'Equal to 0.';
break;
default:
echo 'Something else';
break;
}
查看完整的文档:http ://www.php.net/manual/en/control-structures.switch.php
为什么您的样本结果“小于零”?简单的问题: ($bytes < 0) 评估为假,因为它不是。False 等价于 0,因此它匹配 $bytes 并属于这种情况。
如果您需要匹配某些范围,则必须使用 if-else-constructs。