在PHP中===做什么

Jos*_*ren 5 php comparison operators

我已经用PHP编程了一段时间,但我仍然不理解==和===之间的区别.我知道=是作业.并且==等于.那么===的目的是什么?

Tom*_*ter 26

它比较值和类型相等.

 if("45" === 45) //false
 if(45 === 45) //true
 if(0 === false)//false
Run Code Online (Sandbox Code Playgroud)

它有一个模拟:!==比较类型和价值不平等

 if("45" !== 45) //true
 if(45 !== 45) //false
 if(0 !== false)//true
Run Code Online (Sandbox Code Playgroud)

它对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
Run Code Online (Sandbox Code Playgroud)

这是一个很好的维基百科表,列出了其他语言,类似于三等号.


Tho*_*sen 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
Run Code Online (Sandbox Code Playgroud)

在对象的情况下===比较引用,而不是类型和值(因为$ a和$ b都是相等的类型和值).


Cha*_*rch 6

PHP手册有几个非常好的表("与==的松散比较"和"与===的严格比较"),它们显示了在比较各种变量类型时将给出的结果==和===.