How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

前端 未结 11 2100
故里飘歌
故里飘歌 2020-11-22 16:52

What is the difference between == and === in PHP?

What would be some useful examples?


Additionally, how are these operators us

11条回答
  •  耶瑟儿~
    2020-11-22 17:11

    An addition to the other answers concerning object comparison:

    == compares objects using the name of the object and their values. If two objects are of the same type and have the same member values, $a == $b yields true.

    === compares the internal object id of the objects. Even if the members are equal, $a !== $b if they are not exactly the same object.

    class TestClassA {
        public $a;
    }
    
    class TestClassB {
        public $a;
    }
    
    $a1 = new TestClassA();
    $a2 = new TestClassA();
    $b = new TestClassB();
    
    $a1->a = 10;
    $a2->a = 10;
    $b->a = 10;
    
    $a1 == $a1;
    $a1 == $a2;  // Same members
    $a1 != $b;   // Different classes
    
    $a1 === $a1;
    $a1 !== $a2; // Not the same object
    

提交回复
热议问题