Eds*_*ior 0 php casting boolean
我在工作中遇到了这个问题,并想知道为什么PHP的行为如下:
$test = "insert";
$isInsert1 = $test == "update"; // false
$isInsert2 = (boolean) ($test == "update"); // false
$isInsert3 = (boolean) $test == "update"; // true
Run Code Online (Sandbox Code Playgroud)
$ isInsert3应该像其他两个变量一样返回false,不应该吗?我认为由于某种原因,我不知道,php在将它与"update"字符串进行比较之前考虑了$ test变量.
我希望有人向我解释这种行为.
在第三行中,(boolean) $test == "update"被解释为((boolean) $test) == "update".然后,PHP尝试评估,true == "update"因为非空字符串为true,然后,右侧,"update"转换为true,所以true == true是真的.