简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM