How does in_array check if an object is in an array of objects?

后端 未结 2 1908
轻奢々
轻奢々 2020-12-17 16:33

Does in_array() do object comparison where it checks that all attributes are the same? What if $obj1 === $obj2, will it just do pointer comparison

相关标签:
2条回答
  • 2020-12-17 17:04

    Objects are always references in PHP 5+ and can only be copied (thus creating a new object) by using clone.

    That means you should be able to use in_array().

    0 讨论(0)
  • 2020-12-17 17:24

    in_array() does loose comparisons ($a == $b) unless you pass TRUE to the third argument, in which case it does strict comparisons ($a === $b).

    Semantically, in_array($obj, $arr) is identical to this:

    foreach ($arr as &$member) {
      if ($member == $obj) {
        return TRUE;
      }
    }
    return FALSE;
    

    ...and in_array($obj, $arr, TRUE) is identical to this:

    foreach ($arr as &$member) {
      if ($member === $obj) {
        return TRUE;
      }
    }
    return FALSE;
    

    ...and to quote the manual on what this actually checks:

    When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class.

    On the other hand, when using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.

    0 讨论(0)
提交回复
热议问题