【发布时间】:2020-01-29 20:12:33
【问题描述】:
我不知道出了什么问题。 PHP 只是假设我的数组的 index (int) 0 等价于 Switch 的第一个 Case 并抛出错误。
假设我输入一个这样的数组:
$config = [
"testA" => true,
"testB" => 22,
0 => 0
];
我的代码示例:
foreach($config as $name => $value) {
switch($name) {
case "testA":
if (!is_bool($value)) throw new \Exception( "Configuration '$name' must be boolean.");
$this->systemVarA = $value;
break;
case "testB":
if (!is_int($value)) throw new \Exception( "Configuration '$name' must be integer.");
$this->systemVarB = $value;
break;
}
}
当然 $config["testA"] 和 $config["testB] 可以正常工作,但是当 foreach 到达 $config[0] 的情况下会触发 "testA" 并且应用程序会抛出异常。
我有一个解决方法是在 Switch 之前,像这样转换变量 $name:
$name = (is_int($name) ? (string)$name : $name); // Used this because I already have other inline if
但这似乎是一个错误。我已经在 Windows 主机上测试了 PHP 7.1、7.3 和 7.4。
【问题讨论】:
-
你可以这样做:3v4l.org/uYHWA
标签: php exception integer switch-statement case