开发者

Why does PHP return the first value of an array when referencing said array as an object property?

开发者 https://www.devze.com 2023-02-14 00:10 出处:网络
Why does the second echo line in the following code return (string) \'first\' rather than an array? Code:

Why does the second echo line in the following code return (string) 'first' rather than an array?

Code:

<?php

$foo = simplexml_load_string(<<<EOF
<?xml version='1.0'?> 
<document>
    <body>
        <content>first</content>
        <content>second</content>
    </body>
</document>
EOF
);

echo '<pre>$foo entire object:', "\n", prin开发者_StackOverflow社区t_r($foo, true), "\n";
echo '$foo->body->content: ', "\n", $foo->body->content;

?>

Result:

$foo entire object:
SimpleXMLElement Object
(
    [body] => SimpleXMLElement Object
        (
            [content] => Array
                (
                    [0] => first
                    [1] => second
                )
        )
)

$foo->body->content: 
first


This is not a general PHP feature. Try:

class Foo
{
    public function Foo()
    {
    $this->a = array("foo", "bar");
    }
}
$f = new Foo();
print_r($f->a);

It's a feature of SimpleXML that accessing a property like that gets the first applicable child, which can then be converted to a string.

Though SimpleXML is an extension, you could implement something similar in pure PHP using the _get and _toString magic methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消