Search code examples
phpobjectcomparison

PHP, Objects are automatically converted to 1 on comparison operators


According to documentation, this comparison should return false because "object is always greater"! But instead, the object is automatically converted to 1! Even so, it says that "the object could not be converted to int"! So why is it happening?

http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.types

// php code
$obj=new stdClass();
var_dump($obj==1);

// output
NOTICE Object of class stdClass could not be converted to int on line number 3
bool(true)

you can test it on http://phptester.net/


Solution

  • I think the documentation is either wrong or poorly worded.

    See this site where he dove into the source code...

    https://gynvael.coldwind.pl/?id=492

    The operator basically works in two steps:

    1. If both operands are of a type that the compare_function knows how to compare they are compared. This behavior includes the following pairs of types (please note the equality operator is symmetrical so comparison of A vs B is the same as B vs A):
    • LONG vs LONG
    • LONG vs DOUBLE (+ symmetrical)
    • DOUBLE vs DOUBLE
    • ARRAY vs ARRAY
    • NULL vs NULL
    • NULL vs BOOL (+ symmetrical)
    • NULL vs OBJECT (+ symmetrical)
    • BOOL vs BOOL
    • STRING vs STRING
    • and OBJECT vs OBJECT
    
    1. In case the pair of types is not on the above list the compare_function tries to cast the operands to either the type of the second operand (in case of OBJECTs with cast_object handler), cast to BOOL (in case the second type is either NULL or BOOL), or cast to either LONG or DOUBLE in most other cases. After the cast the compare_function is rerun.

    See my PHP equal operator == reference table for details each specific case.