开发者

Php object-oriented-style date comparison

How do you prefer to compare dates when it comes to OOP? What do you think about:

开发者_开发技巧
$date1 = new Date();
...
$date2 = new Date();

if ($date1 > $date2) {
    ...
}

Please do not put in example anything like strtotime etc., only OOP.


If you're using PHP DateTime objects, you can compare dates using the standard comparison operators. For more info and examples, see the DateTime::diff manual page.

Here is example #2 from the manual:

$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2);
var_dump($date1 < $date2);
var_dump($date1 > $date2);


If Date should have been the internal DateTime class, your code is absolutely fine. But if Date is a custom class, the code will not work as expected. Unlike other programming languages PHP does not allow operator overloading which is required for your code to work. You'd need something that tells PHP how it should work with the comparison operators on instances of your class, because PHP cannot know how to compare $date1 and $date2 and determine which one is larger.

You could however define some comparison methods on your class...

$date1->isLargerThan($date2);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜