PHP:变量赋值的奇怪行为
PHP: Strange behaviour with variable assignment
我正在声明一个 var $t
并为其分配一个值 0。然后我重新分配 $t
一个新值 test
。然后看来 $t
既是 0
又是 test
。这是代码:
$t = 0;
$t = "test";
if($t == 0 && $t == "test"){
echo "unexpected";
}else{
echo "expected";
}
输出为:
"unexpected"
有人可以解释一下这是怎么回事吗? $t
真的同时存在两个不同的值(0
和 test
)还是我遗漏了什么?
您没有追加或串联,所以不应该。请尝试使用相同的比较运算符。
if($t === 0 && $t === "test"){
....
}
这种 "strange" 行为是由于 PHP 的类型转换造成的。由于您使用松散比较 ==
与整数 0
进行比较,因此字符串 test
被转换为整数,从而导致转换为 0
。参见 Loose comparison ==
table。在字符串 php
的行中,您会看到它等于整数 0
,它适用于所有字符串。
您应该使用严格的(类型)比较运算符,即 ===
.
PHP 手动状态:
The value is given by the initial portion of the >string. If the string starts with valid numeric >data, this will be the value used. Otherwise, the >value will be 0 (zero). Valid numeric data is an >optional sign, followed by one or more digits >(optionally containing a decimal point), >followed by an optional exponent. The >exponent is an 'e' or 'E' followed by one or >more digits.
http://il.php.net/manual/en/language.types.string.php#language.types.string.conversion
所以$t == 0
是正确的。你必须使用严格比较 ===
嘿伙计,使用“===”运算符进行比较。
在php中我们可以给一个简单的变量赋任何值,它可以保存数字、浮点数、字符、字符串等
因此始终使用“===”运算符进行唯一或相同的值匹配。
我正在声明一个 var $t
并为其分配一个值 0。然后我重新分配 $t
一个新值 test
。然后看来 $t
既是 0
又是 test
。这是代码:
$t = 0;
$t = "test";
if($t == 0 && $t == "test"){
echo "unexpected";
}else{
echo "expected";
}
输出为:
"unexpected"
有人可以解释一下这是怎么回事吗? $t
真的同时存在两个不同的值(0
和 test
)还是我遗漏了什么?
您没有追加或串联,所以不应该。请尝试使用相同的比较运算符。
if($t === 0 && $t === "test"){
....
}
这种 "strange" 行为是由于 PHP 的类型转换造成的。由于您使用松散比较 ==
与整数 0
进行比较,因此字符串 test
被转换为整数,从而导致转换为 0
。参见 Loose comparison ==
table。在字符串 php
的行中,您会看到它等于整数 0
,它适用于所有字符串。
您应该使用严格的(类型)比较运算符,即 ===
.
PHP 手动状态:
The value is given by the initial portion of the >string. If the string starts with valid numeric >data, this will be the value used. Otherwise, the >value will be 0 (zero). Valid numeric data is an >optional sign, followed by one or more digits >(optionally containing a decimal point), >followed by an optional exponent. The >exponent is an 'e' or 'E' followed by one or >more digits.
http://il.php.net/manual/en/language.types.string.php#language.types.string.conversion
所以$t == 0
是正确的。你必须使用严格比较 ===
嘿伙计,使用“===”运算符进行比较。
在php中我们可以给一个简单的变量赋任何值,它可以保存数字、浮点数、字符、字符串等
因此始终使用“===”运算符进行唯一或相同的值匹配。