如何在PHP中检查对象是否为空?

2022-08-30 07:14:45

如何在PHP中查找对象是否为空。

下面是保存 XML 数据的代码。如何检查它是否为空?$obj

我的代码:

$obj = simplexml_load_file($url);

答案 1

您可以强制转换为数组,然后检查它是否为空

$arr = (array)$obj;
if (!$arr) {
    // do stuff
}

答案 2

编辑:我没有意识到他们想专门检查SimpleXMLElement对象是否为空。我在下面留下了旧的答案

更新的答案(SimpleXMLElement):

对于 SimpleXMLElement:

如果为空,则表示没有属性:

$obj = simplexml_load_file($url);
if ( !$obj->count() )
{
    // no properties
}

$obj = simplexml_load_file($url);
if ( !(array)$obj )
{
    // empty array
}

如果 SimpleXMLElement 是一个层次的深度,并且空,你实际上意味着它只有 PHP 认为 falsey 的属性(或者没有属性):

$obj = simplexml_load_file($url);
if ( !array_filter((array)$obj) )
{
    // all properties falsey or no properties at all
}

如果 SimpleXMLElement 的深度超过一个级别,则可以首先将其转换为纯数组:

$obj = simplexml_load_file($url);
// `json_decode(json_encode($obj), TRUE)` can be slow because
// you're converting to and from a JSON string.
// I don't know another simple way to do a deep conversion from object to array
$array = json_decode(json_encode($obj), TRUE);
if ( !array_filter($array) )
{
    // empty or all properties falsey
}


旧答案(简单对象):

如果要检查简单对象(类型)是否完全为空(无键/值),可以执行以下操作:stdClass

// $obj is type stdClass and we want to check if it's empty
if ( $obj == new stdClass() )
{
    echo "Object is empty"; // JSON: {}
}
else
{
    echo "Object has properties";
}

资料来源:http://php.net/manual/en/language.oop5.object-comparison.php

编辑:添加示例

$one = new stdClass();
$two = (object)array();

var_dump($one == new stdClass()); // TRUE
var_dump($two == new stdClass()); // TRUE
var_dump($one == $two); // TRUE

$two->test = TRUE;
var_dump($two == new stdClass()); // FALSE
var_dump($one == $two); // FALSE

$two->test = FALSE;
var_dump($one == $two); // FALSE

$two->test = NULL;
var_dump($one == $two); // FALSE

$two->test = TRUE;
$one->test = TRUE;
var_dump($one == $two); // TRUE

unset($one->test, $two->test);
var_dump($one == $two); // TRUE

推荐