Countable objects and empty

If you do empty () in an array with no elements in it, you will get true. However, if you do empty () on a countable object with the number 0, you get false. It seems to me that the counter 0 count countable is considered empty. Am I missing something?

<?php class Test implements Countable { public $count = 0; public function count () { return intval (abs ($this -> count)); } } $test = new Test (); var_dump (empty ($test)); var_dump (count ($test)); $test -> count = 10; var_dump (empty ($test)); var_dump (count ($test)); 

I would expect the first call to be empty to return true, but that is not the case.

Is there a reasonable reason for this, or is this a mistake?

+4
source share
2 answers

From docs :

 Returns FALSE if var has a non-empty and non-zero value. The following things are considered to be empty: * "" (an empty string) * 0 (0 as an integer) * 0.0 (0 as a float) * "0" (0 as a string) * NULL * FALSE * array() (an empty array) * var $var; (a variable declared, but without a value in a class) 

I think that $test in your case is still considered Object , which is not in the list of what will empty return as TRUE

+6
source

As stated above, empty() does not consider count($obj) == 0 "empty". The reason for this does not work as expected, because arrays do not implement Countable ie

 array() instanceof Countable // false 

Probably the obvious workaround, but I would decide to post it here.

 function is_empty ($val) { return empty($val) || ($val instanceof Countable && empty(count($val))); } 

Example:

 class Object implements Countable { protected $attributes = array(); // ... public function count () { return count($this->attributes); } } $obj = new Object(); is_empty($obj) // TRUE 

I should note that this solution works in my case, because I would already define is_empty() for prettiness along with other is_* methods.

+2
source

Source: https://habr.com/ru/post/1414344/


All Articles