为什么 PHP 在将数组作为对象属性引用时返回数组的第一个值?
为什么以下代码中的第二个 echo 行返回 (string) 'first' 而不是数组?
代码:
<?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", print_r($foo, true), "\n";
echo '$foo->body->content: ', "\n", $foo->body->content;
?>
结果:
$foo entire object:
SimpleXMLElement Object
(
[body] => SimpleXMLElement Object
(
[content] => Array
(
[0] => first
[1] => second
)
)
)
$foo->body->content:
first
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", print_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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是一般的 PHP 功能。尝试:
这是 SimpleXML 的一个功能,访问这样的属性会获取第一个适用的子属性,然后可以将其转换为字符串。
虽然 SimpleXML 是一个扩展,但您可以使用 _获取 和 _toString 魔术方法。
This is not a general PHP feature. Try:
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.