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.
精彩评论