Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if object property is empty

Tags:

php

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.

like image 634
blee908 Avatar asked Aug 02 '12 03:08

blee908


People also ask

How can you tell if an object has an empty property?

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.

How do you check if an object is empty in HTML?

keys method to check for an empty object. const empty = {}; Object. keys(empty). length === 0 && empty.

How check if object is empty array?

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.

How do you check if an object is empty in node JS?

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.


1 Answers

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);
} 
like image 129
xdazz Avatar answered Sep 30 '22 16:09

xdazz