Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using '<' to compare two objects in PHP

Tags:

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?

like image 606
Arno Lorentz Avatar asked Oct 24 '25 23:10

Arno Lorentz


2 Answers

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: https://www.php.net/manual/en/language.oop5.object-comparison.php#98725

like image 192
WhatHaveYouTriedSoFar Avatar answered Oct 26 '25 13:10

WhatHaveYouTriedSoFar


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" (https://www.php.net/manual/en/language.oop5.object-comparison.php#98725)

  1. you could create your own "compare" method.
like image 36
sammysaglam Avatar answered Oct 26 '25 15:10

sammysaglam