Home  >  Article  >  Backend Development  >  Use the object returned by simplexml_load_string($xml_str) to access non-existent attributes, empty is true

Use the object returned by simplexml_load_string($xml_str) to access non-existent attributes, empty is true

WBOY
WBOYOriginal
2016-08-29 08:50:551245browse

<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?
Use the object returned by simplexml_load_string($xml_str) to access non-existent attributes, empty is true

Reply content:

<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?
Use the object returned by simplexml_load_string($xml_str) to access non-existent attributes, empty is true

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(),

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn