Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

349
Views
Using '<' to compare two objects in PHP

My friend asked me how can she create and compare dates in PHP. Since I knew that there is a DateTime class in PHP I told her to search about it and use it once understood, however I was not sure about the comparison stuff. So I googled how could you compare dates in PHP. I thought the DateTime class uses some inbuilt method to compare dates. But to my surprise, the code looked something like this:

$today_dt = new DateTime($today);
$expire_dt = new DateTime($expire);

if ($expire_dt < $today_dt) { /* Do something */ }

What I don't understand is how can a comparison operator like < be used to compare two 'Objects'. I thought you could only compare primitive datatypes using the comparison operators. So how does PHP compare two 'Objects' using the comparison operators?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

It is not well documented, but when comparing objects, PHP compares member variables one by one in order of declaration, until it finds the first uneven variable, and returns a result based on that.

more details here: http://us3.php.net/manual/en/language.oop5.object-comparison.php#98725

about 4 years ago · Santiago Trujillo Report

0

Yes, usually, you would be correct -> but, for PHP's inbuilt classes, such as DateTime, this is different. https://wiki.php.net/internals/engine/objects#compare_objects.

I wish there was an implementation for a "__compare" magic method to implement comparison. However, for now, you have 2 options:

Edit after reading answer of @WhatHaveYouTriedSoFar above: 1) you could make use of the way PHP compares objects, "the comparison operation stops and returns at the first unequal property found" (http://us3.php.net/manual/en/language.oop5.object-comparison.php#98725)

2) you could create your own "compare" method.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!