如何检查 PHP 对象是否为空(即没有属性)?根据文档,内置的 empty()
不适用于对象:
5.0.0 Objects with no properties are no longer considered empty.
最佳答案
反射类::获取属性
http://www.php.net/manual/en/reflectionclass.getproperties.php
class A {
public $p1 = 1;
protected $p2 = 2;
private $p3 = 3;
}
$a = new A();
$a->newProp = '1';
$ref = new ReflectionClass($a);
$props = $ref->getProperties();
// now you can use $props with empty
echo empty($props);
print_r($props);
/* output:
Array
(
[0] => ReflectionProperty Object
(
[name] => p1
[class] => A
)
[1] => ReflectionProperty Object
(
[name] => p2
[class] => A
)
[2] => ReflectionProperty Object
(
[name] => p3
[class] => A
)
)
*/
请注意 newProp
不会在列表中返回。
获取对象变量
http://php.net/manual/en/function.get-object-vars.php
使用get_object_vars
将返回newProp
,但不会返回protected 和private 成员。
因此,根据您的需要,可能需要结合使用反射和 get_object_vars。
关于php - 如何检查对象是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7562696/