我已经用PHP编程了一段时间,但我仍然不理解==和===之间的区别。我知道=是作业。并且==等于。那么===的目的是什么?
答案 0 :(得分:26)
它比较值和类型相等。
if("45" === 45) //false
if(45 === 45) //true
if(0 === false)//false
它有一个模拟:!==比较类型和值不等式
if("45" !== 45) //true
if(45 !== 45) //false
if(0 !== false)//true
对于像strpos这样的函数特别有用 - 它可以有效地返回0。
strpos("hello world", "hello") //0 is the position of "hello"
//now you try and test if "hello" is in the string...
if(strpos("hello world", "hello"))
//evaluates to false, even though hello is in the string
if(strpos("hello world", "hello") !== false)
//correctly evaluates to true: 0 is not value- and type-equal to false
Here's a good wikipedia table列出了与三等号类似的其他语言。
答案 1 :(得分:12)
确实===比较了值和类型,但是有一种情况尚未提及,那就是将对象与==和===进行比较。
给出以下代码:
class TestClass {
public $value;
public function __construct($value) {
$this->value = $value;
}
}
$a = new TestClass("a");
$b = new TestClass("a");
var_dump($a == $b); // true
var_dump($a === $b); // false
如果是对象===比较引用,而不是类型和值(因为$ a和$ b都是相同的类型和值)。
答案 2 :(得分:6)
PHP手册有a couple of very nice tables(“与==的松散比较”和“与===的严格比较”),显示了比较各种变量类型时将给出的结果==和===。
答案 3 :(得分:4)
它将检查数据类型是否与值
相同if ("21" == 21) // true
if ("21" === 21) // false
答案 4 :(得分:3)
===
比较值 和 类型。
答案 5 :(得分:2)
==不比较类型,===不。
0 == false
评估为true但
0 === false
没有
答案 6 :(得分:0)
这是一次真正的平等比较。
"" == False
例如true
。
"" === False
是false
答案 7 :(得分:0)
最低限度,===比==更快,因为没有自动施法/强制进行,但它的极小,几乎不值得一提。 (当然,我刚提到它......)