我在一些PHP代码中遇到了一个非常奇怪和令人担忧的问题。我拥有的一个变量在IF语句中返回true,而它显然应该返回false。
$pr = $_SESSION['fin_print_printer']; //this should equal 0
print $pr; //this returns 0, as it should
if($pr == "L"){
print "local";
} else {
print "serve";
}
print $pr; //this returns 0 again, as it should
这在我的脚本中打印"local"(在两个零之间),而不打印"serve"。我的项目中有超过100000行代码,我还没有遇到过这个问题,现在我不知道发生了什么
如果我做If($pr==="L"),那么它可以像预期的那样工作,但上面的没有。
PHP正试图将'L'类型转换为int,结果为0。
intval('L'); // 0
将您的代码更改为以下内容,以便将类型考虑在内:
if($pr === "L")
{
print "local";
}
else
{
print "serve";
}
或者手动将$pr
转换为字符串。
// You can also to (string)$pr ("0" instead of 0)
if(strval($pr) == "L")
{
print "local";
}
else
{
print "serve";
}
如果你使用typecasting(我没有检查):
if ( (string)$pr == "L" ) {
print "local";
} else {
print "serve";
}
鲜为人知的方法:您也可以像一样进行选角
if ("L" == $pr) {
由于比较松散,PHP将右值强制转换为左值的类型,正如您已经知道的,当string(1)"L"
强制转换为int(0)
时,int(0)
强制转换为string(1)"0"
。