代码之家  ›  专栏  ›  技术社区  ›  Josh Curren

php中的==操作

  •  5
  • Josh Curren  · 技术社区  · 16 年前

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

    8 回复  |  直到 16 年前
        1
  •  26
  •   Tom Ritter    16 年前

    它比较了值和类型相等性。

     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 列出与三等号类似的其他语言。

        2
  •  12
  •   Thorbjørn Hermansen    16 年前

    确实,==比较值和类型,但有一种情况尚未被提及,那就是当您将对象与==和==进行比较时。

    给出以下代码:

    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的类型和值都相同)。

        3
  •  6
  •   Chad Birch    16 年前

    PHP手册有 a couple of very nice tables (“loose comparisons with==”和“strict comparisons with==”)显示在比较各种变量类型时,==和==将给出什么结果。

        4
  •  4
  •   Oli    16 年前

    它将检查数据类型是否与值相同

    if ("21" == 21) // true
    if ("21" === 21) // false
    
        5
  •  3
  •   Andrew Hare    16 年前

    === 比较价值 类型。

        6
  •  2
  •   Marc W    16 年前

    ==不比较类型,==比较类型。

    0 == false
    

    计算结果为true,但

    0 === false
    

        7
  •  0
  •   Oli    16 年前

    这是一个真正的平等比较。

    "" == False 例如 true .

    "" === False false

        8
  •  0
  •   Justin    16 年前

    最小,==比==快,因为没有自动铸造/合作进行,但它是如此之小,几乎不值得一提。(当然,我刚才提到过……)

    推荐文章