PHP 日期时间比较

Ser*_*der 5 php comparison datetime

我已经习惯于在 PHP (===) 中使用相同的比较运算符,而不是相等的比较运算符 (==)。我在使用 php 内置的 DateTime 对象时遇到了一个问题。我很困惑为什么在下面的代码中相等比较返回 true,但相同的比较返回 false?

代码:

$test1 = new DateTime("now");       // What I thought were identical objects
$test2 = new DateTime("now");       // 
$test3 = new DateTime("tomorrow");

echo("test1: ");
var_dump($test1);
echo("<br/>test2: ");
var_dump($test2);

echo("now === now: ");
var_dump($test1 === $test2);

echo("<br/>now == now: ");
var_dump($test1 == $test2);

echo("<br/>now < now: ");
var_dump($test1 < $test2);

echo("<br/>now > now: ");
var_dump($test1 > $test2);

echo("<br/>now < tomorrow: ");
var_dump($test2 < $test3);

echo("<br/>now > tomorrow: ");
var_dump($test2 > $test3);
Run Code Online (Sandbox Code Playgroud)

输出:

    test1: object(DateTime)#36 (3) { ["date"]=> string(19) "2015-06-23 14:44:25" ["timezone_type"]=> int(3) ["timezone"]=> string(15) "America/Chicago" } 
    test2: object(DateTime)#37 (3) { ["date"]=> string(19) "2015-06-23 14:44:25" ["timezone_type"]=> int(3) ["timezone"]=> string(15) "America/Chicago" } 
    now === now: bool(false) 
    now == now: bool(true) 
    now < now: bool(false) 
    now > now: bool(false) 
    now < tomorrow: bool(true) 
    now > tomorrow: bool(false)
Run Code Online (Sandbox Code Playgroud)

Ana*_*Die 4

在对象比较的情况下,===不仅检查值和对象类型,而且还会检查引用。这就是为什么在你的情况下===由于两个单独的实例而返回 false 的原因。

只是为了澄清一下:-

https://eval.in/386378

注意:- 在第一种情况下,有两个单独的实例$test1$test2,这就是为什么===即使对象类型和值相等也会返回 false 的原因。

但在第二种情况下,因为$test1$test2是相同的引用,所以它指出true

另外,对于普通变量,===仅检查值和数据类型。一如既往==,仅检查值,每当数据类型不同时,它都不会给出正确的输出。所以使用时要小心==。谢谢。