I would like to check, if any of the properties of an object is empty, without manually checking each one. This is how I do it now:
class MyClass {
public $a;
public $b;
public $c;
}
Then:
$item = new MyClass();
// ...
$item->a = 10;
$item->b = 20;
// ...
// TODO:
$hasEmpty = empty($item->a) || empty($item->b) || empty($item->c);
How is it possible without manually checking each property?
CodePudding user response:
You can actually typecast object to an array and then use array_filter
on it to filter out the empty values and check it's size like below:
<?php
$hasEmpty = count(array_filter((array)$item,fn($v) => empty($v))) > 0;
var_dump($hasEmpty);
Another way could be by implementing ArrayAccess
interface and accessing object keys just like array keys and performing the empty checks, but I will leave it upto the reader to implement them as an exercise if they wish to.
CodePudding user response:
I suggest destructuring your object and then loop through and see if any are null.
// create class
class MyClass {
public $a;
public $b;
public $c;
}
// create object
$item = new MyClass();
$item->a = 10;
$item->b = 20;
// get vars and test if any properties are null
$vars = get_object_vars($item);
$isNull = false;
foreach($vars as $var){
if(empty($var)){
$isNull = true;
}
}
or you could turn this into a function
function areAnyPropertiesEmpty($class){
$vars = get_object_vars($class);
$isNull = false;
foreach($vars as $var){
if(empty($var)){
$isNull = true;
}
}
return $isNull;
}
CodePudding user response:
I think you have to loop through the object.
function isObjectEmpty($obj) {
foreach ($obj as $value) {
if (!isset($value)) {
return true;
}
}
return false;
}
CodePudding user response:
The best way is to use PHP Reflection. This sample code checks ALL properties:
<?php
$item = new MyClass();
$reflect = new ReflectionClass($item);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);
$is_empty = false;
foreach ($props as $prop) {
if (empty($prop->getValue())) {
$is_empty = true;
// We break, since it's useless to continue over
break;
}
}
// Test it
var_dump($is_empty);
?>