如何在 PHP 中检查对象是否为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9412126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check that an object is empty in PHP?
提问by sandbox
How to find if an object is empty or not in PHP.
如何在 PHP 中查找对象是否为空。
Following is the code in which $obj
is holding XML data. How can I check if it's empty or not?
以下是$obj
保存 XML 数据的代码。我如何检查它是否为空?
My code:
我的代码:
$obj = simplexml_load_file($url);
回答by Peter Kelly
You can cast to an array and then check if it is empty or not
您可以转换为数组,然后检查它是否为空
$arr = (array)$obj;
if (!$arr) {
// do stuff
}
回答by Timothy Zorn
Edit: I didn't realize they wanted to specifically check if a SimpleXMLElement object is empty. I left the old answer below
编辑:我没有意识到他们想要专门检查 SimpleXMLElement 对象是否为空。我在下面留下了旧答案
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
回答by Mohamed23gharbi
You can cast your object into an array, and test its count like so:
您可以将对象转换为数组,并像这样测试它的计数:
if(count((array)$obj)) {
// doStuff
}
回答by stamat
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. 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.
这是我在 JavaScript 中使用的一个非常简单的解决方案。与上述将对象转换为数组并检查它是否为空或将其编码为 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
. If it's not empty it will enter the foreach
loop and return false
right away, not passing through the whole set.
该解决方案的工作方式非常简单:如果对象为空,它根本不会进入 foreach 循环,并且将返回true
。如果它不为空,它将进入foreach
循环并立即返回false
,而不是通过整个集合。
回答by kenorb
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()
在对象上使用它时,Using不会像往常一样工作,因为__isset()
如果声明了重载方法,则会调用它。
Therefore you can use count()
(if the object is Countable).
因此您可以使用count()
(如果对象是Countable)。
Or by using get_object_vars()
, e.g.
或者通过使用get_object_vars()
,例如
get_object_vars($obj) ? TRUE : FALSE;
回答by biziclop
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 ) );
回答by biziclop
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)
回答by roosevelt
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. Use the following code:
如果您将 PHP 中的任何内容转换为 (bool),它会立即告诉您该项目是对象、原始类型还是 null。使用以下代码:
$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!";
}
回答by nem75
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. But how is PHP to know? Some objects are never meant to represent content (think factories for instance), others always represent a meaningful value (think new DateTime()
).
“空”对象不能有通用定义。你可能会在上面的例子中争论empty()
应该的结果true
,因为对象不代表任何内容。但是 PHP 怎么知道呢?一些对象从不代表内容(例如认为工厂),其他对象总是代表有意义的值(认为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()
方法。
回答by Muhammad Tahir
$array = array_filter($array);
if(!empty($array)) {
echo "not empty";
}
or
或者
if(count($array) > 0) {
echo 'Error';
} else {
echo 'No Error';
}