PHP:如何检查对象的属性是否具有值?

时间:2013-10-12 13:24:17

标签: php stdclass php-5.4

我用它来检查对象是否具有属性

function objectHasProperty($input){
        return (is_object($input) && (count(get_object_vars($input)) > 0)) ? true : false;
 }

但是我想进一步检查以确保所有属性都有值,例如

stdClass Object
        (
            [package] => 
            [structure] => 
            [app] => 
            [style] => 
            [js] => 
        )

如果所有属性都有空值,我想返回false。可能吗?任何提示和想法?

3 个答案:

答案 0 :(得分:14)

有几种方法可以做到这一点,一直到使用PHP的反射API,但只是检查一个对象的所有公共属性是否为空,你可以这样做:

$properties = array_filter(get_object_vars($object));
return !empty($properties);

(临时变量$properties是必需的,因为您使用的是PHP 5.4。)

答案 1 :(得分:2)

对于深度检查和更高级的处理,我会选择以下类似的东西,这些东西很容易扩展。将它视为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)

答案 2 :(得分:1)

根据您认为的“空值”,您可能会调整删除不需要的值的回调函数:

function objectHasProperty($input){
    return (
        is_object($input) 
        && 
        array_filter(
            get_object_vars($input), 
            function($val){ 
                // remove empty strings and null values
                return (is_string($val) && strlen($val))||($val!==null); 
            }
        )
    ) ? true : false;
}

$y = new stdClass;
$y->zero = 0;

$n = new stdClass;
$n->notset = null;

var_dump(objectHasProperty($y),objectHasProperty($n));//true,false