Comparing Objects in PHP

SO

Problem

This is not well known, but PHP allows you to compare objects - and not only on equality ==- but also on <and on >. But how does it work? So, if I want to create comparable objects - what restrictions / rules should they follow?

The most useful case is objects DateTime()- they have a specific timestamp, and they can be compared (and this makes logical sense). There is some explanation for lxr for DateTime. But what about the usual case?

I have:

class C
{
   protected $holder;
   protected $mirror;
   public function __construct($h = null)
   {
      $this->holder=$h;
      $this->mirror=-1*$h;
   }
}


$one = new C(1);
$two = new C(2);
//false, false, true: used $holder
var_dump($one>$two, $one==$two, $one<$two);

-If I reorder ads he will use $mirror:

class C
{
   //only order changed:
   protected $mirror;
   protected $holder;
   public function __construct($h = null)
   {
      $this->holder=$h;
      $this->mirror=-1*$h;
   }
}

$one = new C(1);
$two = new C(2);
//true, false, false: used $mirror
var_dump($one>$two, $one==$two, $one<$two);

, , "" . protected .

:

class Test
{
  protected $a;
  protected $b;

  function __construct($a, $b)
  {
    $this->a = $a;
    $this->b = $b;
  }
}

$x = new Test(1, 2);
$y = new Test(1, 3);

// true, false, false
var_dump($x < $y, $x == $y, $x > $y);

$x = new Test(3, 1);
$y = new Test(2, 1);

// false, false, true
var_dump($x < $y, $x == $y, $x > $y);

- . - . , . ,

: , ? , :

  • , PHP ?
  • , ? (.. )
  • protected/private ?

e.t.c. - , //, - , . ==/===. , - , false ().

+4
3

PHP ( ) . , , , PHP.

, , " ".

+3

php ( c-) ,

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 , " " -1,0,1 , ( strcmp() ).
, () , .
, , DateTime "" DateTime, , DateTime compare_objects , .

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;

, , DateTime, date_object_compare_date.

( cmp (o1, o2) == 0), , zend_std_compare_objects. StdClass, , ,

<?php
class Foo { }
$a = new StdClass;
$b = new Foo;

$a > $b;

( php-) . DateTime, ArrayObject, PDOStatement, Closures .
/ script ( /)

+2

PHP, , .

[...] , FALSE. , [sic] , .

:

[...] , , , , , , , , , , ; . [...] , .

, , . .

0

Source: https://habr.com/ru/post/1532626/


All Articles