PHP If then和switch语句不起作用


PHP If then and switch statement not working

好的,首先,这是一个非常特殊的问题。我在PHP上工作了很长时间,我不知道为什么会发生这种情况。

我有一个函数adminUpdate。此函数将返回true。我设置它总是返回true进行测试。

然后我让函数取那个结果。

static function result2JSON($result,$options = array()) {
        if($result == "permission") {
            echo "permission";
        }
        if($result == true) {
            echo "true";
        }

        switch ($result) {
            case 'permission':
                die($result."xxx permission");
                $json = self::setJSON("Permission");
                break;
            case 'exist':
                $json = self::setJSON("Exist");
                break;
            case false:
                $json = self::setJSON("Error");
                break;
            case "":
                $json = self::setJSON("Error");
                break;
            case 1 :
                $json = self::setJSON("OK");
                break;
            case true:
                $json = self::setJSON("OK");
                break;
            default:
                $json = self::setJSON("OK");
                break;
        }

        $json = array_merge($json,$options);

        return $json;
    }

这些"回声"用于测试这种情况。因此,$result在被这个函数获取之前总是=true。

但这是我得到的输出:

permissiontrueResult = 1 IN permission section

这意味着开关上的$result=Permission,然后==true,然后=="Permission"。为什么?

您可能希望使用标识检查===而不是相等性检查。

在php中,非空字符串被解释为true。

$result = "permission";
if($result)
     echo 'String interpreted as true';

看看php.net上的布尔页面(短)http://php.net/manual/en/language.types.boolean.php和PHP比较运算符页面。。。http://www.php.net/manual/en/language.operators.comparison.php

如果您尝试将包含内容的字符串视为布尔值,则其求值结果为true。(好吧,字符串"0"的计算结果为False。php很奇怪。)

因此,如果你想看看一个变量是否真的是真的,你必须使用一个同时检查类型的比较:

if ($result === "permission") { ... }
if ($result === True) { ... }

您应该将每次出现的==替换为===