Successfully parsed SimpleXMLElement comparison to 'false' returning 'true'

后端 未结 3 1624
抹茶落季
抹茶落季 2021-01-21 04:11

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

The code:

$simplexml = simplexml_load_string($xmlstring);
var_dump($simplexml);
var_         


        
相关标签:
3条回答
  • 2021-01-21 04:41

    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?

    0 讨论(0)
  • 2021-01-21 04:58

    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

    0 讨论(0)
  • 2021-01-21 04:58
    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 */ }
    
    0 讨论(0)
提交回复
热议问题