在PHP的比较操作中,空和空是否相同?

在PHP的比较操作中,空和空是否相同?,php,arrays,object,operators,is-empty,Php,Arrays,Object,Operators,Is Empty,我有一个类,它有一个方法,该方法期望从数组格式的API服务得到响应。然后,此方法通过强制转换(object)$response\u array将响应数组转换为对象。在此之后,该方法尝试解析对象的内容。返回的数组可能为空。在分析class方法中对象的内容之前,我在if…else块中检查null或空对象。我想使用一个等价比较运算符,比如if($response\u object==null){}而不是if(empty($response\u object)){}。 下面是我的班级的样子 <?p

我有一个类,它有一个方法,该方法期望从数组格式的API服务得到响应。然后,此方法通过强制转换
(object)$response\u array
将响应数组转换为对象。在此之后,该方法尝试解析对象的内容。返回的数组可能为空。在分析class方法中对象的内容之前,我在
if…else
块中检查null或空对象。我想使用一个等价比较运算符,比如
if($response\u object==null){}
而不是
if(empty($response\u object)){}
。 下面是我的班级的样子

<?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()
,并且它是一致的吗?如果没有,那么如何修改此代码以获得一致的结果。这将帮助我知道
null
empty
在PHP对象中是否表示相同的含义。如果我仍然可以使用类似的比较,我将不胜感激。看看这个例子

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

所以,在您的案例中,将对象与null进行比较不是一个好主意。更多信息:

这不是检查空对象的正确方法。如果使用空数组调用函数parseResponse,则
If
条件仍将为false

因此,如果您将
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
。。。将输出

非空

如果测试
空($response\u object)
,也会发生同样的情况。这在很久以前是不同的,但从PHP5.0(2004年年中)开始,没有属性的对象不再被认为是空的

您应该只在已经拥有的数组上进行测试,该数组为空时会出错。所以你可以写:

        if(!$response_array) {
          echo "null";
        }
        else {
          echo "not null";
        }
或者,如果您确实想要(in)相等,那么请执行
$response\u array==false
,确保使用
=
而不是
=
。但就我个人而言,我发现这种与布尔文字的比较只不过是浪费空间

以下所有选项都是
if
条件下的工作备选方案:

基于$response\u数组:

基于$response\u对象:


请注意,
get\u object\u vars
如果$response\u对象不是标准对象,并且具有继承属性,则可能会给出与数组强制转换方法不同的结果。

在强制转换到对象之前,可能会重复使用
empty()
。此代码应该在终端中测试,对吗?这听起来很有用。因此,从技术上讲,我得到的是,我无法通过使用
null
empty()
一致地测试空对象。在转换到
(object)
之前,我必须首先测试有问题的
数组()。不过,对于我的应用程序逻辑来说,这听起来很棘手——让我想想这是否是我想要做的。谢谢你的回复。是的,在铸造前测试是最简单的。但是,当您仍然可以访问原始阵列进行测试时,没有什么可以阻止您首先进行强制转换。但是,如果您已经将数组强制转换为对象,并且此时无法再测试原始数组(出于某些应用程序逻辑原因),请选择最后提到的选项之一:
!获取对象变量($response\u object)
!(数组)($response\u object)
。我觉得这两种方法中的第一种更具可读性。
!$response_array
!count($response_array)
count($response_array) === 0
empty($response_array)
!get_object_vars($response_object)
!(array)($response_object)