简体   繁体   English

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

[英]How to check that an object is empty in PHP?

How to find if an object is empty or not in PHP.如何在 PHP 中查找对象是否为空。

Following is the code in which $obj<\/code> is holding XML data.以下是$obj<\/code>保存 XML 数据的代码。 How can I check if it's empty or not?如何检查它是否为空?

My code:我的代码:

$obj = simplexml_load_file($url);

You can cast to an array and then check if it is empty or not您可以转换为数组,然后检查它是否为空

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

Edit : I didn't realize they wanted to specifically check if a SimpleXMLElement object is empty.编辑:我没有意识到他们想要专门检查 SimpleXMLElement 对象是否为空。 I left the old answer below我在下面留下了旧答案

Updated Answer (SimpleXMLElement) :更新答案(SimpleXMLElement)

For SimpleXMLElement:对于 SimpleXMLElement:

If by empty you mean has no properties:如果空的意思是没有属性:

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

OR或者

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

If SimpleXMLElement is one level deep, and by empty you actually mean that it only has properties PHP considers falsey (or no properties):如果 SimpleXMLElement 是一层深,并且为空,则实际上意味着它只有PHP 认为为 false 的属性(或没有属性):

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

If SimpleXMLElement is more than one level deep, you can start by converting it to a pure array:如果 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
}


Old Answer (simple object) :旧答案(简单对象)

If you want to check if a simple object (type stdClass ) is completely empty (no keys/values), you can do the following:如果您想检查一个简单对象(类型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";
}

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

Edit : added example编辑:添加示例

$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

You can cast your object into an array, and test its count like so:您可以将对象转换为数组,并像这样测试它的计数:

if(count((array)$obj)) {
   // doStuff
}

Imagine if the object is not empty and in a way quite big, why would you waste the resources to cast it to array or serialize it...想象一下,如果对象不是空的并且在某种程度上相当大,你为什么要浪费资源将它转换为数组或序列化它......

This is a very easy solution I use in JavaScript.这是我在 JavaScript 中使用的一个非常简单的解决方案。 Unlike the mentioned solution that casts an object to array and check if it is empty, or to encode it into JSON, this simple function is very efficient concerning used resources to perform a simple task.与上述将对象转换为数组并检查它是否为空或将其编码为 JSON 的解决方案不同,这个简单的函数对于执行简单任务的已用资源非常有效。

function emptyObj( $obj ) {
    foreach ( $obj AS $prop ) {
        return FALSE;
    }

    return TRUE;
}

The solution works in a very simple manner: It wont enter a foreach loop at all if the object is empty and it will return true .该解决方案以非常简单的方式工作:如果对象为空,它根本不会进入 foreach 循环,它将返回true If it's not empty it will enter the foreach loop and return false right away, not passing through the whole set.如果它不为空,它将进入foreach循环并立即返回false ,而不是通过整个集合。

Using empty() won't work as usual when using it on an object, because the __isset() overloading method will be called instead, if declared.在对象上使用empty()时,它不会像往常一样工作,因为如果声明了__isset()重载方法将被调用。

Therefore you can use count() (if the object is Countable ).因此您可以使用count() (如果对象是Countable )。

Or by using get_object_vars() , eg或者通过使用get_object_vars() ,例如

get_object_vars($obj) ? TRUE : FALSE;

Another possible solution which doesn't need casting to array :另一种不需要强制转换为array可能解决方案:

// test setup
class X { private $p = 1; } // private fields only => empty
$obj = new X;
// $obj->x = 1;


// test wrapped into a function
function object_empty( $obj ){
  foreach( $obj as $x ) return false;
  return true;
}


// inline test
$object_empty = true;
foreach( $obj as $object_empty ){ // value ignored ... 
  $object_empty = false; // ... because we set it false
  break;
}


// test    
var_dump( $object_empty, object_empty( $obj ) );

there's no unique safe way to check if an object is empty没有唯一的安全方法来检查对象是否为空

php's count() first casts to array, but casting can produce an empty array, depends by how the object is implemented (extensions' objects are often affected by those issues) php 的 count() 首先转换为数组,但转换可以产生一个空数组,这取决于对象的实现方式(扩展的对象通常受这些问题的影响)

in your case you have to use $obj->count();在您的情况下,您必须使用 $obj->count();

http://it.php.net/manual/en/simplexmlelement.count.php http://it.php.net/manual/en/simplexmlelement.count.php

(that is not php's count http://www.php.net/count ) (这不是 php 的计数http://www.php.net/count

If you cast anything in PHP as a (bool), it will tell you right away if the item is an object, primitive type or null.如果您将 PHP 中的任何内容转换为 (bool),它会立即告诉您该项目是对象、原始类型还是 null。 Use the following code:使用以下代码:

$obj = simplexml_load_file($url);

if (!(bool)$obj) {
    print "This variable is null, 0 or empty";
} else {
    print "Variable is an object or a primitive type!";
}

in PHP version 8在 PHP 版本 8 中

consider you want to access a property of an object, but you are not sure that the object itself is null or not and it could cause error.考虑您要访问对象的属性,但您不确定该对象本身是否为空,并且可能会导致错误。 in this case you can use Nullsafe operator that introduced in php 8 as follow:在这种情况下,您可以使用 php 8中引入的Nullsafe operator ,如下所示:

 $country = $session?->user?->getAddress()?->country;

I was using a json_decode of a string in post request.我在发布请求中使用了字符串的 json_decode。 None of the above worked for me, in the end I used this:以上都不适合我,最后我使用了这个:

$post_vals = json_decode($_POST['stuff']);

if(json_encode($post_vals->object) != '{}')
{
    // its not empty
}
$array = array_filter($array);
if(!empty($array)) {
    echo "not empty";
}

or或者

if(count($array) > 0) {
    echo 'Error';
} else {
    echo 'No Error';
}

Simply check if object type is null or not.只需检查对象类型是否为空。

if( $obj !== null )
{
     // DO YOUR WORK
}

Based on this answer from kenorb, here's another one-liner for objects with public vars:根据 kenorb 的这个答案,这里有另一个用于具有公共变量的对象的单行代码:

if (!empty(get_object_vars($myObj))) { ... }

For objects with private or protected vars, better to cast to an array as others have mentioned.对于具有私有或受保护变量的对象,最好像其他人提到的那样转换为数组。

If an object is "empty" or not is a matter of definition, and because it depends on the nature of the object the class represents, it is for the class to define.一个对象是否为“空”是一个定义问题,因为它取决于类所代表的对象的性质,所以由类来定义。

PHP itself regards every instance of a class as not empty. PHP 本身认为类的每个实例都不是空的。

class Test { }
$t = new Test();
var_dump(empty($t));

// results in bool(false)

There cannot be a generic definition for an "empty" object. “空”对象不能有通用定义。 You might argue in the above example the result of empty() should be true , because the object does not represent any content.你可能会在上面的例子中争辩说empty()的结果应该是true ,因为对象不代表任何内容。 But how is PHP to know?但是 PHP 怎么知道呢? Some objects are never meant to represent content (think factories for instance), others always represent a meaningful value (think new DateTime() ).一些对象从不代表内容(例如工厂),其他对象总是代表有意义的值(想想new DateTime() )。

In short, you will have to come up with your own criteria for a specific object, and test them accordingly, either from outside the object or from a self-written isEmpty() method in the object.简而言之,您必须为特定对象提出自己的标准,并相应地测试它们,无论是从对象外部还是从对象中自写的isEmpty()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM