【问题标题】:PHP Switch enter in string Case when integer indexed整数索引时PHP切换输入字符串大小写
【发布时间】: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。

【问题讨论】:

标签: php exception integer switch-statement case


【解决方案1】:

那是因为 PHP 在 switch 部分使用了 == 运算符。 当您尝试将 int(0) 与字符串 "testA" 进行比较时,它总是返回 true。 检查它:

if(0 == "some string") echo "Equals!";

此代码打印“等于!”。

【讨论】:

  • 这是正确的......这是由试图将字符串内容“转换”为整数的松散类型系统引起的。一旦遇到第一个非数字字符,这个过程就会停止(例如. 在这个例子中立即)...转换的结果是 0(零)
  • 知道了!!寻找这个“==”比较器问题我发现了其他解决方法:switch(TRUE){case ("testA" === $name): //blah break;}
  • @BrunoNatali 查看我对更清洁解决方案的回答
  • @StephenR 我看到了你的解决方案,但我已经得到了这个演员方法的解决方法,正如我在原始问题中提到的那样。谈到 switch 中的“真正”技巧,我选择了这个而不是使用 if & else if,以保持良好的 switch 结构并在其他程序员阅读我的代码时提供良好的视觉效果。
【解决方案2】:

弗拉基米尔的回答正确地确定了原因。这是一个修复:将测试值转换为字符串,因为您正在与字符串进行比较。

switch( (string) $name ) {
    ...
}

是的,您可以使用switch(TRUE){case ("testA" === $name): ... }“反转技巧”,但到那时,您不妨只使用elseif

【讨论】:

    猜你喜欢
    • 2013-02-01
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    相关资源
    最近更新 更多