Weird bug when variable takes the value of a object
It's like this:
$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's the problem here? Why does empty() return true?
I guess you expect that empty will return true
only for NULL
while actually whole set of values is considered to be "empty values"; from doc:
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)
What is your variable set to? 0, false, empty strings and some others are considered empty. Try isset() instead and see if it works. In this case, you'll have to print your message when isset() is false.
Which is the value of $var
after gets the $obj->data->field
?
according to the man page "0" and "0.0" and others are all considered empty.
My guess: $obj->data->field
"is" an object and the class does not implement the __isset() method as you'd need it in order to use empty() this way.
What does
echo "type:", gettype($obj->data), " class:", get_class($obj->data);
print?
self-contained 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#
精彩评论