Using '<' to compare two objects in PHP

A friend of mine asked me how she can create and compare dates in PHP. Since I knew there was a class in PHP DateTime

, I told her to look for it and use it as soon as I understood, however I was not sure about comparing the material. So, I googled how you could compare dates in PHP. I thought the class DateTime

uses some built-in 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 */ }

      

I don't understand how to use the comparison operator, for example <

to compare two "objects". I thought you could compare primitive data types using comparison operators. So how does PHP compare two "Objects" using comparison operators?

+3


source share


2 answers


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



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

+8


source


Yes, usually you would be right -> but for PHP built-in classes like DateTime this is different. https://wiki.php.net/internals/engine/objects#compare_objects .

I want an implementation of the magic method "__compare" to be implemented to implement the comparison. However, for now, you have 2 options:



Edit after reading @WhatHaveYouTriedSoFar answer above: 1) you can use PHP object comparison way: "comparison operation stops and returns on first unequal property found" ( http://us3.php.net/manual/en/language.oop5.object -comparison.php # 98725 )

2) you can create your own comparison method.

+1


source







All Articles