一个奇怪的 PHP 对象
我正在使用 SimpleXML 从 API 获取一些数据。它以这种格式返回内容:
object(SimpleXMLElement)#10 (1) {
[0]=>
string(36) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
我的问题是,我如何访问该对象的字符串值?如果我尝试执行 $myVariable->0
,则会出现错误。执行 $zero = '0'
然后 echo $myVariable->$zero
也不起作用,(array) $myVariable
也不起作用> 工作(发出警告)。
I'm using SimpleXML to get some data from an API. Its returning things in this format:
object(SimpleXMLElement)#10 (1) {
[0]=>
string(36) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
My question is, how can I possibly access the string value of this object? If I try to do $myVariable->0
that gives me an error. Doing $zero = '0'
and then echo $myVariable->$zero
doesn't work either, nor does (array) $myVariable
work (that gives a warning).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
诀窍是
SimpleXMLElement
有__toString
实现的魔术方法将返回您的string(36) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
,因此要获取您刚刚转换的字符串SimpleXMLElement
对象上的 (string):使用
PHP
当然可以,因此这里不一定需要显式的
(string)
。The trick is that
SimpleXMLElement
has__toString
magic method implemented that would return yourstring(36) "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
, so to get this string you just cast (string) on yourSimpleXMLElement
object:With
PHP
you canof course, so explicit
(string)
here is not necessarily needed.AFAIR 它是这样的:
编辑:这在大多数情况下都有效,但不是这个。看起来SimpleXML不仅实现了Nemoden指出的
__toString
方法,而且还实现了__get
,因此以这种方式访问对象属性会导致返回克隆对象。AFAIR it's like this:
Edit: That would work in majority of cases, but not this one. It looks like SimpleXML implements not only
__toString
method like Nemoden pointed out, but also__get
, so that accessing object properties in this way results in cloned object being returned.