Successfully parsed SimpleXMLElement comparison to

2019-02-25 01:24发布

问题:

I got a very awkward and specific issue with a simplexml evaluation.

The code:

$simplexml = simplexml_load_string($xmlstring);
var_dump($simplexml);
var_dump($simplexml == false); //this comparison

var_dump($simplexml) returns the actual structure of my simplexml but the comparison returns 'true' for this specific simplexml, which I can't show the structure because of my contract.
I'm sure that's very specifc issue 'cause I tried other XML strings and the comparison returns 'false'.

$simplexml = simplexml_load_string('<a><b>test</b></a>');
var_dump($simplexml); //returns the actual structure
var_dump($simplexml == false); //returns false

I solved the problem using the '===' operator, but I'm not satisfied with just making it work. I want to understand why the '==' operator returns true.
I read about the two operators and the SimpleXMLElement and on my sight it should return 'false' for both operators. What are the possible reasons for a comparison between a succesfully parsed SimpleXMLElement and the boolean 'false' to return 'true'?

回答1:

Have a look here: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

It says that SimpleXML objects created from empty tags evaluate to false. Maybe that's what's going on?



回答2:

I this this is a better way to do it using boolean casting (bool)

$simplexml = simplexml_load_string('<a><b>test</b></a>');
var_dump($simplexml); //returns the actual structure
var_dump((bool) $simplexml); // Retuns true
var_dump((bool) $simplexml == false); //returns false
var_dump((bool) $simplexml === false); //returns false   

Demo : http://codepad.viper-7.com/xZtuNG

=== compares values and type… except with objects, where === is only true if both operands are actually the same object! For objects, == compares both value (of every attribute) and type, which is what === does for every other type.

EDIT 1

See Latest Bug on Something similar https://bugs.php.net/bug.php?id=54547



回答3:

var_dump($simplexml == false); //returns false

This is expected behavior and it is explained by data comparison via "loose" data typing. In PHP, NULL, zero, and boolean FALSE are considered "Falsy" values; everything else is considered "Truthy." Inside the parentheses, PHP performs an evaluation of the expression. In this case, PHP evaluates a comparison of the named variable OBJECT and the boolean FALSE. They are not the same, so the return value from the comparison is FALSE and this is what *var_dump()* prints.

You can use this to your advantage in the if() statement. Example:

$simplexml = SimpleXML_Load_String('<a><b>test</b></a>');
if ($simplexml) { /* process the object */ }
else { /* process the failure to load the XML */ }