1

Having an issue where literal comparing of 2 Carbon objects are not equal, and I'm not sure why, I have posted my tinker session below to show the problem;

>>> $t = Carbon\Carbon::today()
=> Carbon\Carbon @1548025200 {#3026
     date: 2019-01-21 00:00:00.0 Europe/Berlin (+01:00),
   }
>>> $f = Carbon\Carbon::parse('21-01-2019 10:02:01')->startOfDay()
=> Carbon\Carbon @1548025200 {#3035
     date: 2019-01-21 00:00:00.0 Europe/Berlin (+01:00),
   }
>>> $f === $t
=> false
>>> $f == $t
=> true
>>> echo $t
2019-01-21 00:00:00⏎
>>> echo $f
2019-01-21 00:00:00⏎
>>> 

Just wondering why $f === $t is false,

Thanks for anyone that can help!

Also even using today() for both returns false; (But in case either of these have different solutions, the first example is more applicable to my issue)

>>> $t = Carbon\Carbon::today()
=> Carbon\Carbon @1548025200 {#3033
     date: 2019-01-21 00:00:00.0 Europe/Berlin (+01:00),
   }
>>> $f = Carbon\Carbon::today()
=> Carbon\Carbon @1548025200 {#3038
     date: 2019-01-21 00:00:00.0 Europe/Berlin (+01:00),
   }
>>> $f === $t
=> false
>>> $f == $t
=> true
Robert Pounder
  • 1,490
  • 1
  • 14
  • 29
  • 1
    Manual maybe http://php.net/manual/en/language.oop5.object-comparison.php? – u_mulder Jan 21 '19 at 11:27
  • This is how the `===` operator works for objects. See [this answer](https://stackoverflow.com/a/589748/157957), and this sentence in the manual: "When using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class." – IMSoP Jan 21 '19 at 11:41
  • I did read the manual, but I misread/understood identical classes matching due to the duplicating the object example ($p = $o) – Robert Pounder Jan 22 '19 at 10:02

1 Answers1

2

You should use Carbon's comparison functions to avoid those issues.

namelivia
  • 2,657
  • 1
  • 21
  • 24
  • 2
    Well, in this case you don't avoid an issue, because there is no issue in checking 2 objects equality with the identity operator.. as the result will be always true if they are both refering to the same instance or false otherwise... – Mihai Matei Jan 21 '19 at 11:38
  • it's fine for my purpose, I just did `->diffInDays === 0`, thanks – Robert Pounder Jan 22 '19 at 09:59