I feel like I'm missing something here. I've been using PHP's empty()
function for quite a while now in determining if a variable is empty. I wanted to use it to determine if an object's property is empty, but somehow it doesn't work. Here's a simplified class to illustrate the problem
// The Class
class Person{
private $number;
public function __construct($num){
$this->number = $num;
}
// this the returns value, even though its a private member
public function __get($property){
return intval($this->$property);
}
}
// The Code
$person = new Person(5);
if (empty($person->number)){
echo "its empty";
} else {
echo "its not empty";
}
So basically, the $person
object should have a value (5) in its number property. As you might have guessed, the problem is that php echoes "its empty". But it's not!!!
However, it does work if I store the property in a variable, then evaluate it.
So what would be the best way to determine if an object property is empty? Thank you.
Use the Object. entries() function. It returns an array containing the object's enumerable properties. If it returns an empty array, it means the object does not have any enumerable property, which in turn means it is empty.
keys method to check for an empty object. const empty = {}; Object. keys(empty). length === 0 && empty.
To check if an array is empty or not, you can use the . length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not.
Object. keys(myObj). length === 0; As there is need to just check if Object is empty it will be better to directly call a native method Object.
You need to implement __isset() magic method.
__isset() is triggered by calling isset() or empty() on inaccessible properties.
public function __isset($property){
return isset($this->$property);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With