【发布时间】:2018-10-05 17:54:28
【问题描述】:
我在一个非常基本的 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 = (integer)$_GET["variable"];到 $variable = $_GET["variable"];。因为您使用的是显式转换,每次它以 char 形式将变量值更改为整数时
-
我不建议使用具有不同表达方式的开关。将它用于具有不同值的相同表达式。阅读文档以查看交换机的主要用例。 “switch 语句类似于 同一表达式 上的一系列 IF 语句”。 php.net/manual/en/control-structures.switch.php
-
我知道您使用 switch 进行值比较,使用 if´s 进行条件比较。我只是想在这里看到我的逻辑错误。
标签: php nginx switch-statement php-7.1