如何检查一个 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
,但受保护和私有成员不会被返回。
get_object_vars
。$reflect = new ReflectionClass($theclass);
$properties = $reflect->getProperties();
if(empty($properties)) {
//Empty Object
}
你能用一些代码来详细说明吗?我不明白你想要实现什么。
无论如何,你都可以像这样在对象上调用一个函数:
public function IsEmpty()
{
return ($this->prop1 == null && $this->prop2 == null && $this->prop3 == null);
}
__isset()
的实现,并根据设置了哪些属性返回相应的值。