0

According to the Carbon docs:

$first = Carbon::create(2012, 9, 5, 23, 26, 11);
$second = Carbon::create(2012, 9, 5, 20, 26, 11, 'America/Vancouver');

var_dump($first <= $second);     // bool(true)

The latter comparison works!!! Why?

All I can find on the internet is

objects are compared by recursively comparing their properties in the order that they are defined, which includes public, protected, and private properties.

So I suspect the Carbon instance has the datetime 2012-09-05 23:26:11[*] as its first property and so it gets compared, but that raises so many questions and I can't "step into" the comparison with XDebug.

Has anyone a good explanation for this?

[*] Dates in ISO format can be compared in string form.

raveren
  • 17,799
  • 12
  • 70
  • 83

1 Answers1

0

Ok after writing this question I think I might have found the answer, per PHP documentation:

https://www.php.net/manual/en/datetime.diff.php#example-2091

Note:

DateTimeImmutable and DateTime objects can be compared using comparison operators.

Which leads to:

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

Built-in classes can define its own comparison.

And

class Carbon extends DateTime // ...

So Carbon extends an inbuilt class, which supports comparison between its objects.

The comparison works because PHP developers made an exception for DateTime objects and hardcoded it into the C-source of PHP language.

raveren
  • 17,799
  • 12
  • 70
  • 83
  • I would not describe it as exception, but this is it. In my experience, though, I find it more reliable to convert both operands to UTC. There're a few subtle bugs in a few places, related to DST and crossing timezone boundaries in comparisons. – Álvaro González Jun 24 '23 at 06:53
  • "I would not describe it as exception" - "exception" - noun a person or thing that is excluded from a general statement or does not follow a rule. – raveren Jun 26 '23 at 07:22
  • Also Carbon takes care of the timezone conversions as it deliberately and elegantly demonstrates in the quoted example from its documentation. – raveren Jun 26 '23 at 07:24