Objects comparison in PHP

前端 未结 3 341
小蘑菇
小蘑菇 2021-01-13 13:55

SO,

The problem

It\'s not well-known, but PHP allows to compare objects - and not just on equality == - but on <

3条回答
  •  礼貌的吻别
    2021-01-13 14:31

    Each class in php has an associated structure (in the c code) of handler functions, it looks like

    struct _zend_object_handlers {
        /* general object functions */
        zend_object_add_ref_t                   add_ref;
        zend_object_del_ref_t                   del_ref;
    [...]
        zend_object_compare_t                   compare_objects;
    [...]
    };
    

    compare_objects points to a function that "takes two objects" and returns -1,0,1 according to whatever this comparator defines as the order (just like strcmp() does for strings).
    This function is used only when both operands (objects) point to the same comparision function - but let's just stick with this case.
    That's where e.g. DateTime "adds" its feature to compare two DateTime instances, it just defines another, DateTime-specific compare_objects function and puts it in the structure describing its class.

    static void date_register_classes(TSRMLS_D)
    {
    [...]
    
        INIT_CLASS_ENTRY(ce_date, "DateTime", date_funcs_date);
        ce_date.create_object = date_object_new_date;
    [...]
        date_object_handlers_date.compare_objects = date_object_compare_date;
    

    So if you want to know (exactly) how two DateTime instances are compared, take a look at date_object_compare_date.

    The comparision described in the manual (at least for the case cmp(o1,o2)==0) seems to be implemented in zend_std_compare_objects. And it's used by both StdClass and a simple user defined class like e.g.

     $b;
    

    But other classes (in php extensions) do set other functions. DateTime, ArrayObject, PDOStatement, even Closures use different functions.
    But I haven't found a way to define a comparision function/method in script code (but haven't looked too hard/long)

提交回复
热议问题