对于深入检查和更高级的处理,我会选择以下易于扩展的内容。将其视为对 dev-null-dweller 的回答的后续回答(这是完全有效的并且是一个很好的解决方案)。
/**
* Deep inspection of <var>$input</var> object.
*
* @param mixed $input
* The variable to inspect.
* @param int $visibility [optional]
* The visibility of the properties that should be inspected, defaults to <code>ReflectionProperty::IS_PUBLIC</code>.
* @return boolean
* <code>FALSE</code> if <var>$input</var> was no object or if any property of the object has a value other than:
* <code>NULL</code>, <code>""</code>, or <code>[]</code>.
*/
function object_has_properties($input, $visibility = ReflectionProperty::IS_PUBLIC) {
set_error_handler(function(){}, E_WARNING);
if (is_object($input)) {
$properties = (new ReflectionClass($input))->getProperties($visibility);
$c = count($properties);
for ($i = 0; $i < $c; ++$i) {
$properties[$i]->setAccessible(true);
// Might trigger a warning!
$value = $properties[$i]->getValue($input);
if (isset($value) && $value !== "" && $value !== []) {
restore_error_handler();
return true;
}
}
}
restore_error_handler();
return false;
}
// Some tests
// The bad boy that emits a E_WARNING
var_dump(object_has_properties(new \mysqli())); // boolean(true)
var_dump(object_has_properties(new \stdClass())); // boolean(false)
var_dump(object_has_properties("")); // boolean(false)
class Foo {
public $prop1;
public $prop2;
}
var_dump(object_has_properties(new Foo())); // boolean(false)
$foo = new Foo();
$foo->prop1 = "bar";
var_dump(object_has_properties($foo)); // boolean(true)