PHP中的比较操作中的Empty和NULL是否相同?

Is Empty and NULL the same in a comparision operation in PHP?

我有一个 class 有一个方法,它期望来自 API 服务的数组格式的响应。然后,此方法通过强制转换 (object)$response_array 将响应数组转换为对象。在此之后,该方法尝试解析对象的内容。返回的数组有可能为空。在我的 class 方法中解析对象的内容之前,我在 if...else 块中执行 null 或空对象检查。我想使用 if($response_object === null){} 而不是 if(empty($response_object)){} 这样的等价比较运算符。 下面是我的 class 的样子

<?php 
class ApiCall {

    //this method receives array response, converts to object and then parses object
    public function parseResponse(array $response_array)
    {
        $response_object = (object)$response_array;

        //check if this object is null
        if($response_object === null) //array with empty content returned
        {
          #...do something

        }
        else //returned array has content 
        {
           #...do something

        }

    }

}
?>

所以我的问题是 - 这是在不使用函数 empty() 的情况下检查空对象的正确方法吗?它是否一致?如果不是,那么我如何修改此代码以获得一致的结果。这将帮助我了解 nullempty 在 PHP 对象中的含义是否相同。如果我仍然可以使用这样的等效比较,我将不胜感激 ===

看这个例子

$ php -a
php > $o = (object)null;
php > var_dump($o);
class stdClass#2 (0) {
}
php > var_dump(!$o);
bool(false)

因此,在您的情况下将对象与 null 进行比较并不是一个好主意。更多相关信息:How to check that an object is empty in PHP?

检查空对象的方法不正确。如果您使用空数组调用函数 parseResponse,则 if 条件仍然为假。

因此,如果您将 echo 放入 if-else 代码中,如下所示:

class ApiCall {
    //this method receives array response, converts to object and then parses object
    public function parseResponse(array $response_array)
    {
        $response_object = (object)$response_array;
        //check if this object is null
        if($response_object === null) { // not doing what you expect
          echo "null";
        }
        else {
          echo "not null";
        }
    }
}

然后这个调用:

ApiCall::parseResponse(array()); // call with empty array

...将输出

not null

如果您测试 empty($response_object),也会发生同样的情况。这在遥远的过去曾经是不同的,但是从 PHP 5.0(2004 年中)开始,没有属性的对象不再被认为是空的。

你应该只测试你已有的数组,当它为空时是假的。所以你可以写:

        if(!$response_array) {
          echo "null";
        }
        else {
          echo "not null";
        }

或者,如果您真的想要(不)相等,则执行 $response_array == false,确保使用 == 而不是 ===。但就个人而言,我发现这种与布尔文字的比较无非是浪费 space.

以下所有内容都可以替代 if 条件:

基于$response_array:

!$response_array
!count($response_array)
count($response_array) === 0
empty($response_array)

基于$response_object:

!get_object_vars($response_object)
!(array)($response_object)

请注意,如果 $response_object 不是标准对象,并且会具有继承属性,则 get_object_vars 可能会给出与数组转换方法不同的结果.