Home > Article > Backend Development > Use the object returned by simplexml_load_string($xml_str) to access non-existent attributes, empty is true
<code>$xml_str = <<<EOT <xml> <fee_type><![CDATA[CNY]]></fee_type> <return_code><![CDATA[SUCCESS]]></return_code> <trade_type><![CDATA[NATIVE]]></trade_type> </xml> EOT; $obj = simplexml_load_string($xml_str); var_dump($obj->game); if(empty($obj->game)) { echo '空的'; } else { echo "不空"; } </code>
The game attribute does not exist, but var_dump has results. Why?
<code>$xml_str = <<<EOT <xml> <fee_type><![CDATA[CNY]]></fee_type> <return_code><![CDATA[SUCCESS]]></return_code> <trade_type><![CDATA[NATIVE]]></trade_type> </xml> EOT; $obj = simplexml_load_string($xml_str); var_dump($obj->game); if(empty($obj->game)) { echo '空的'; } else { echo "不空"; } </code>
The game attribute does not exist, but var_dump has results. Why?
Although the game
attribute does not exist, when directly obtaining this attribute, the magic method __get()
of SimpleXMLElement
will be called. This method returns an empty object and is printed out by var_dump
.
But the object should be true when empty()
is judged. Why is it false here?
Because empty()
is not equal to a direct Boolean judgment, but empty($var) === isset($var) && $var
, so the magic method __isset( of
SimpleXMLElement will be called first) )
, and __isset()
returns that this attribute does not exist, and the following __get()
is automatically skipped.
Because simplexmlelement
internally implements setter
and getter
, just like the magic methods __set()
and __get()
,