php - Php Switch Case 未按预期工作
问题描述
我在一个非常基本的PHP脚本中犯了一个非常愚蠢的逻辑错误。
有关结论,请参见 u_mulders 答案。
脚本访问一个 $_GET[] 变量,并且应该只确定该变量是否已设置(非常有效)以及它是否设置为大于 0 的值(这未按预期工作)。
这里是“switch.php”文件:
<?php
if($_GET["variable"]==NULL){
die('Set $_GET["variable"] to use this Script!');
}
//Create Instance of $_GET["variable"] casted to Integer
$variable = (integer)$_GET["variable"];
//this var_dump displays that the $variable is succesfully casted to an Integer
var_dump($variable);
switch ($variable) {
case ($variable > 0):
echo "You entered $variable!";
break;
default:
echo "Either Your variable is less than 0, or not a Number!";
break;
}
?>
现在我希望第一个 case-Statement 仅在 $variable 大于 0 时运行。
如果我打开网址,情况并非如此:http ://www.someserver.com/switch.php?variable=0
输出如下:
.../switch.php:11:int 0
您输入了 0!
我希望你能帮助我。
提前致谢。
解决方案
所以, $variable
is 0
, case $variable > 0
which 0 > 0
is false
。
比较0
和false
。你得到了什么?当然——真的。
重写你switch
的:
// compare not `$variable` but result of some operation with `true`
switch (true) {
case ($variable > 0):
echo "You entered $variable!";
break;
default:
echo "Either Your variable is less than 0, or not a Number!";
break;
}
推荐阅读
- xamarin - MvvmCross 6 RecyclerView 多按钮项绑定
- mysql - 为每个组或默认选择前 X 条记录
- wordpress - 没有尾随/的链接的WordPress站点重定向问题
- java - 如果我无法使用注释标记该类,如何在反序列化期间为类自定义 json 包装键?
- sql - 带有日期列的完全外部自联接
- c - 避免 POSIX 线程中的内存泄漏
- java - 如何通过 config.properties 从 pom.xml 获取参数值
- javascript - problem with conditions in javascript while working with DOM
- c - Why I have error: deprecated conversion from string constant to 'char*' [-Wwrite-strings] in the line 5 and 6?
- facebook - Drupal 8 - 简单的 fb 连接失败