Weird error when a variable takes an object value

This is true:

$var = $obj->data->field; echo $var; // works, I get the value of 'field' if(empty($var)) echo '$var is empty!'; // I get this message too. wtf? 

What is the problem? Why does empty () return true?

+4
source share
4 answers

My guess: $obj->data->field "is" an object, and the class does not implement the __ isset () method, because you need it to use empty () this way.

What is he doing

 echo "type:", gettype($obj->data), " class:", get_class($obj->data); 

print?


standalone example to demonstrate the effect:

 <?php class Bar { public $flag=false; public function __isset($key) { return $this->flag; } public function __get($key) { return '#'.$key.'#'; } } $foo = new StdClass; $foo->bar = new Bar; echo empty($foo->bar->test) ? 'empty':'not empty', ", ", $foo->bar->test, "\n"; $foo->bar->flag = true; echo empty($foo->bar->test) ? 'empty':'not empty', ", ", $foo->bar->test, "\n"; 

prints

 empty, #test# not empty, #test# 
+3
source

I assume that you expect empty to return true only for NULL , while in fact the entire set of values โ€‹โ€‹is considered a "null value"; from the document :

 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) 
+4
source

What is your variable? 0, false, empty lines and some others are considered empty. Try isset () and see if it works. In this case, you will need to print your message if isset () is false.

+4
source

What is the value of $var after getting $obj->data->field ?

according to the man page "0" and "0.0", while others are considered empty.

+4
source

All Articles